<!DOCTYPE html><html><head>
  <meta charset="utf-8">
  <base data-ice="baseUrl" href="/v5/./">
  <title data-ice="title">Manual | Sequelize</title>
  <link type="text/css" rel="stylesheet" href="/v5/css/style.css">
  <link type="text/css" rel="stylesheet" href="/v5/css/prettify-tomorrow.css">
  <script src="/v5/script/prettify/prettify.js"></script>
  <script src="/v5/script/manual.js"></script>
<link rel="stylesheet" href="/v5/./inject/css/0-style.css"><link rel="stylesheet" href="/v5/./inject/css/0-theme.css"><meta name="description" content="An easy-to-use multi SQL dialect ORM for Node.js"><meta property="twitter:card" content="summary"><meta property="twitter:title" content="Sequelize"><meta property="twitter:description" content="An easy-to-use multi SQL dialect ORM for Node.js"><meta name="robots" content="noindex"></head>
<body class="layout-container manual-root manual-index" data-ice="rootContainer">

<header>
  <a href="/v5/./" style="display: flex; align-items: center;"><img src="/v5/./image/brand_logo.png" style="width:34px;"></a>
  
  <a href="/v5/identifiers.html" class="api-reference-link">API Reference</a>
  <a href="/v5/source.html">Source</a>
  
  <div class="search-box">
  <span>
    <img src="/v5/./image/search.png">
    <span class="search-input-edge"></span><input class="search-input"><span class="search-input-edge"></span>
  </span>
    <ul class="search-result"></ul>
  </div>
<a style="" href="https://github.com/sequelize/sequelize"><img width="30px" src="/v5/./image/github.png" style="width: 30px;"></a>
      <a href="https://sequelize.org/slack">
        <img src="/v5/manual/asset/slack.svg" style="width: 60px; margin-left: -15px;">
      </a>
    </header>

<nav class="navigation" data-ice="nav"><div class="manual-toc-root">
  

    <div class="manual-group">
      <a href="/v5/index.html" style="color: black">Home</a>
    </div>
  
      <div class="manual-group" style="pointer-events: none">
        Core Concepts
      </div>
    <div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html" data-ice="link">Getting started</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#installing" data-ice="link">Installing</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#setting-up-a-connection" data-ice="link">Setting up a connection</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#note--setting-up-sqlite" data-ice="link">Note: setting up SQLite</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#note--connection-pool--production-" data-ice="link">Note: connection pool (production)</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#testing-the-connection" data-ice="link">Testing the connection</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#closing-the-connection" data-ice="link">Closing the connection</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#modeling-a-table" data-ice="link">Modeling a table</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#changing-the-default-model-options" data-ice="link">Changing the default model options</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#synchronizing-the-model-with-the-database" data-ice="link">Synchronizing the model with the database</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#synchronizing-all-models-at-once" data-ice="link">Synchronizing all models at once</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#note-for-production" data-ice="link">Note for production</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#querying" data-ice="link">Querying</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/getting-started.html"><a href="/v5/manual/getting-started.html#promises-and-async-await" data-ice="link">Promises and async/await</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/dialects.html"><a href="/v5/manual/dialects.html" data-ice="link">Dialects</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/dialects.html"><a href="/v5/manual/dialects.html#mysql" data-ice="link">MySQL</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/dialects.html"><a href="/v5/manual/dialects.html#mariadb" data-ice="link">MariaDB</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/dialects.html"><a href="/v5/manual/dialects.html#sqlite" data-ice="link">SQLite</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/dialects.html"><a href="/v5/manual/dialects.html#postgresql" data-ice="link">PostgreSQL</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/dialects.html"><a href="/v5/manual/dialects.html#mssql" data-ice="link">MSSQL</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html" data-ice="link">Datatypes</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html#array-enum-" data-ice="link">Array(ENUM)</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html#range-types" data-ice="link">Range types</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html#special-cases" data-ice="link">Special Cases</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html#extending-datatypes" data-ice="link">Extending datatypes</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html#postgresql" data-ice="link">PostgreSQL</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/data-types.html"><a href="/v5/manual/data-types.html#ranges" data-ice="link">Ranges</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html" data-ice="link">Model definition</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#timestamps" data-ice="link">Timestamps</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#deferrable" data-ice="link">Deferrable</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#getters--amp--setters" data-ice="link">Getters &amp; setters</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#defining-as-part-of-a-property" data-ice="link">Defining as part of a property</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#defining-as-part-of-the-model-options" data-ice="link">Defining as part of the model options</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#helper-functions-for-use-inside-getter-and-setter-definitions" data-ice="link">Helper functions for use inside getter and setter definitions</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#validations" data-ice="link">Validations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#per-attribute-validations" data-ice="link">Per-attribute validations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#per-attribute-validators-and--code-allownull--code-" data-ice="link">Per-attribute validators and allowNull</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#model-wide-validations" data-ice="link">Model-wide validations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#configuration" data-ice="link">Configuration</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#import" data-ice="link">Import</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#optimistic-locking" data-ice="link">Optimistic Locking</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#database-synchronization" data-ice="link">Database synchronization</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#expansion-of-models" data-ice="link">Expansion of models</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-definition.html"><a href="/v5/manual/models-definition.html#indexes" data-ice="link">Indexes</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html" data-ice="link">Model usage</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#data-retrieval---finders" data-ice="link">Data retrieval / Finders</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-find--code----search-for-one-specific-element-in-the-database" data-ice="link">find - Search for one specific element in the database</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-findorcreate--code----search-for-a-specific-element-or-create-it-if-not-available" data-ice="link">findOrCreate - Search for a specific element or create it if not available</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-findandcountall--code----search-for-multiple-elements-in-the-database--returns-both-data-and-total-count" data-ice="link">findAndCountAll - Search for multiple elements in the database, returns both data and total count</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-findall--code----search-for-multiple-elements-in-the-database" data-ice="link">findAll - Search for multiple elements in the database</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#complex-filtering---or---not-queries" data-ice="link">Complex filtering / OR / NOT queries</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#manipulating-the-dataset-with-limit--offset--order-and-group" data-ice="link">Manipulating the dataset with limit, offset, order and group</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#raw-queries" data-ice="link">Raw queries</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-count--code----count-the-occurrences-of-elements-in-the-database" data-ice="link">count - Count the occurrences of elements in the database</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-max--code----get-the-greatest-value-of-a-specific-attribute-within-a-specific-table" data-ice="link">max - Get the greatest value of a specific attribute within a specific table</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-min--code----get-the-least-value-of-a-specific-attribute-within-a-specific-table" data-ice="link">min - Get the least value of a specific attribute within a specific table</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#-code-sum--code----sum-the-value-of-specific-attributes" data-ice="link">sum - Sum the value of specific attributes</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#eager-loading" data-ice="link">Eager loading</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#top-level-where-with-eagerly-loaded-models" data-ice="link">Top level where with eagerly loaded models</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#including-everything" data-ice="link">Including everything</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#including-soft-deleted-records" data-ice="link">Including soft deleted records</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#ordering-eager-loaded-associations" data-ice="link">Ordering Eager Loaded Associations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#nested-eager-loading" data-ice="link">Nested eager loading</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/models-usage.html"><a href="/v5/manual/models-usage.html#use-right-join-for-association" data-ice="link">Use right join for association</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html" data-ice="link">Hooks</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#order-of-operations" data-ice="link">Order of Operations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#declaring-hooks" data-ice="link">Declaring Hooks</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#removing-hooks" data-ice="link">Removing hooks</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#global---universal-hooks" data-ice="link">Global / universal hooks</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#default-hooks--sequelize-options-define-" data-ice="link">Default Hooks (Sequelize.options.define)</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#permanent-hooks--sequelize-addhook-" data-ice="link">Permanent Hooks (Sequelize.addHook)</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#connection-hooks" data-ice="link">Connection Hooks</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#instance-hooks" data-ice="link">Instance hooks</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#model-hooks" data-ice="link">Model hooks</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#associations" data-ice="link">Associations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#a-note-about-transactions" data-ice="link">A Note About Transactions</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/hooks.html"><a href="/v5/manual/hooks.html#internal-transactions" data-ice="link">Internal Transactions</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/querying.html"><a href="/v5/manual/querying.html" data-ice="link">Querying</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/querying.html"><a href="/v5/manual/querying.html#attributes" data-ice="link">Attributes</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/querying.html"><a href="/v5/manual/querying.html#where" data-ice="link">Where</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/querying.html"><a href="/v5/manual/querying.html#basics" data-ice="link">Basics</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/querying.html"><a href="/v5/manual/querying.html#operators" data-ice="link">Operators</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#range-operators" data-ice="link">Range Operators</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#combinations" data-ice="link">Combinations</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#operators-aliases" data-ice="link">Operators Aliases</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#operators-security" data-ice="link">Operators security</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/querying.html"><a href="/v5/manual/querying.html#json" data-ice="link">JSON</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#postgresql" data-ice="link">PostgreSQL</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#mssql" data-ice="link">MSSQL</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/querying.html"><a href="/v5/manual/querying.html#jsonb" data-ice="link">JSONB</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#nested-object" data-ice="link">Nested object</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#nested-key" data-ice="link">Nested key</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/querying.html"><a href="/v5/manual/querying.html#containment" data-ice="link">Containment</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/querying.html"><a href="/v5/manual/querying.html#relations---associations" data-ice="link">Relations / Associations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/querying.html"><a href="/v5/manual/querying.html#pagination---limiting" data-ice="link">Pagination / Limiting</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/querying.html"><a href="/v5/manual/querying.html#ordering" data-ice="link">Ordering</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/querying.html"><a href="/v5/manual/querying.html#table-hint" data-ice="link">Table Hint</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/querying.html"><a href="/v5/manual/querying.html#index-hints" data-ice="link">Index Hints</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/instances.html"><a href="/v5/manual/instances.html" data-ice="link">Instances</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#building-a-non-persistent-instance" data-ice="link">Building a non-persistent instance</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#creating-persistent-instances" data-ice="link">Creating persistent instances</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#updating---saving---persisting-an-instance" data-ice="link">Updating / Saving / Persisting an instance</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#destroying---deleting-persistent-instances" data-ice="link">Destroying / Deleting persistent instances</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#restoring-soft-deleted-instances" data-ice="link">Restoring soft-deleted instances</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#working-in-bulk--creating--updating-and-destroying-multiple-rows-at-once-" data-ice="link">Working in bulk (creating, updating and destroying multiple rows at once)</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#values-of-an-instance" data-ice="link">Values of an instance</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#reloading-instances" data-ice="link">Reloading instances</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#incrementing" data-ice="link">Incrementing</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/instances.html"><a href="/v5/manual/instances.html#decrementing" data-ice="link">Decrementing</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/associations.html"><a href="/v5/manual/associations.html" data-ice="link">Associations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#basic-concepts" data-ice="link">Basic Concepts</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#source--amp--target" data-ice="link">Source &amp; Target</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#foreign-keys" data-ice="link">Foreign Keys</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#underscored-option" data-ice="link">underscored option</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#cyclic-dependencies--amp--disabling-constraints" data-ice="link">Cyclic dependencies &amp; Disabling constraints</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#enforcing-a-foreign-key-reference-without-constraints" data-ice="link">Enforcing a foreign key reference without constraints</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#one-to-one-associations" data-ice="link">One-To-One associations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#belongsto" data-ice="link">BelongsTo</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#foreign-keys" data-ice="link">Foreign keys</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#target-keys" data-ice="link">Target keys</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#hasone" data-ice="link">HasOne</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#source-keys" data-ice="link">Source keys</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#difference-between-hasone-and-belongsto" data-ice="link">Difference between HasOne and BelongsTo</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#one-to-many-associations--hasmany-" data-ice="link">One-To-Many associations (hasMany)</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#belongs-to-many-associations" data-ice="link">Belongs-To-Many associations</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#source-and-target-keys" data-ice="link">Source and target keys</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#naming-strategy" data-ice="link">Naming strategy</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#associating-objects" data-ice="link">Associating objects</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#check-associations" data-ice="link">Check associations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/associations.html"><a href="/v5/manual/associations.html#advanced-concepts" data-ice="link">Advanced Concepts</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#scopes" data-ice="link">Scopes</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#1-n" data-ice="link">1:n</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#n-m" data-ice="link">n:m</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/associations.html"><a href="/v5/manual/associations.html#creating-with-associations" data-ice="link">Creating with associations</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#belongsto---hasmany---hasone-association" data-ice="link">BelongsTo / HasMany / HasOne association</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#belongsto-association-with-an-alias" data-ice="link">BelongsTo association with an alias</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/associations.html"><a href="/v5/manual/associations.html#hasmany---belongstomany-association" data-ice="link">HasMany / BelongsToMany association</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/raw-queries.html"><a href="/v5/manual/raw-queries.html" data-ice="link">Raw queries</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/raw-queries.html"><a href="/v5/manual/raw-queries.html#-quot-dotted-quot--attributes" data-ice="link">"Dotted" attributes</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/raw-queries.html"><a href="/v5/manual/raw-queries.html#replacements" data-ice="link">Replacements</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/raw-queries.html"><a href="/v5/manual/raw-queries.html#bind-parameter" data-ice="link">Bind Parameter</a></li>
</ul>
  </div>

      <div class="manual-group" style="pointer-events: none">
        Other Topics
      </div>
    <div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html" data-ice="link">Transactions</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#managed-transaction--auto-callback-" data-ice="link">Managed transaction (auto-callback)</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#throw-errors-to-rollback" data-ice="link">Throw errors to rollback</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#automatically-pass-transactions-to-all-queries" data-ice="link">Automatically pass transactions to all queries</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#concurrent-partial-transactions" data-ice="link">Concurrent/Partial transactions</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#without-cls-enabled" data-ice="link">Without CLS enabled</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#isolation-levels" data-ice="link">Isolation levels</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#unmanaged-transaction--then-callback-" data-ice="link">Unmanaged transaction (then-callback)</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#usage-with-other-sequelize-methods" data-ice="link">Usage with other sequelize methods</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#after-commit-hook" data-ice="link">After commit hook</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/transactions.html"><a href="/v5/manual/transactions.html#locks" data-ice="link">Locks</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/scopes.html"><a href="/v5/manual/scopes.html" data-ice="link">Scopes</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/scopes.html"><a href="/v5/manual/scopes.html#definition" data-ice="link">Definition</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/scopes.html"><a href="/v5/manual/scopes.html#usage" data-ice="link">Usage</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/scopes.html"><a href="/v5/manual/scopes.html#merging" data-ice="link">Merging</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/scopes.html"><a href="/v5/manual/scopes.html#merging-includes" data-ice="link">Merging includes</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/scopes.html"><a href="/v5/manual/scopes.html#associations" data-ice="link">Associations</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/read-replication.html"><a href="/v5/manual/read-replication.html" data-ice="link">Read replication</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html" data-ice="link">Migrations</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#the-cli" data-ice="link">The CLI</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#installing-cli" data-ice="link">Installing CLI</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#bootstrapping" data-ice="link">Bootstrapping</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#configuration" data-ice="link">Configuration</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#creating-first-model--and-migration-" data-ice="link">Creating first Model (and Migration)</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#running-migrations" data-ice="link">Running Migrations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#undoing-migrations" data-ice="link">Undoing Migrations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#creating-first-seed" data-ice="link">Creating First Seed</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#running-seeds" data-ice="link">Running Seeds</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#undoing-seeds" data-ice="link">Undoing Seeds</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#advance-topics" data-ice="link">Advance Topics</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#migration-skeleton" data-ice="link">Migration Skeleton</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#the--code--sequelizerc--code--file" data-ice="link">The .sequelizerc File</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#dynamic-configuration" data-ice="link">Dynamic Configuration</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#using-babel" data-ice="link">Using Babel</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#using-environment-variables" data-ice="link">Using Environment Variables</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#specifying-dialect-options" data-ice="link">Specifying Dialect Options</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#production-usages" data-ice="link">Production Usages</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#storage" data-ice="link">Storage</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#migration-storage" data-ice="link">Migration Storage</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#seed-storage" data-ice="link">Seed Storage</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#configuration-connection-string" data-ice="link">Configuration Connection String</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#passing-dialect-specific-options" data-ice="link">Passing Dialect Specific Options</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#programmatic-use" data-ice="link">Programmatic use</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/migrations.html"><a href="/v5/manual/migrations.html#query-interface" data-ice="link">Query Interface</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/resources.html"><a href="/v5/manual/resources.html" data-ice="link">Resources</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/resources.html"><a href="/v5/manual/resources.html#addons--amp--plugins" data-ice="link">Addons &amp; Plugins</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#acl" data-ice="link">ACL</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#auto-code-generation--amp--scaffolding" data-ice="link">Auto Code Generation &amp; Scaffolding</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#autoloader" data-ice="link">Autoloader</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#caching" data-ice="link">Caching</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#filters" data-ice="link">Filters</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#fixtures---mock-data" data-ice="link">Fixtures / mock data</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#hierarchies" data-ice="link">Hierarchies</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#historical-records---time-travel" data-ice="link">Historical records / Time travel</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#migrations" data-ice="link">Migrations</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#slugification" data-ice="link">Slugification</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#tokens" data-ice="link">Tokens</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/resources.html"><a href="/v5/manual/resources.html#miscellaneous" data-ice="link">Miscellaneous</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/typescript.html"><a href="/v5/manual/typescript.html" data-ice="link">TypeScript</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/typescript.html"><a href="/v5/manual/typescript.html#installation" data-ice="link">Installation</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/typescript.html"><a href="/v5/manual/typescript.html#usage" data-ice="link">Usage</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/typescript.html"><a href="/v5/manual/typescript.html#usage-of--code-sequelize-define--code-" data-ice="link">Usage of sequelize.define</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html" data-ice="link">Upgrade to v5</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#breaking-changes" data-ice="link">Breaking Changes</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#support-for-node-6-and-up" data-ice="link">Support for Node 6 and up</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#secure-operators" data-ice="link">Secure Operators</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#typescript-support" data-ice="link">Typescript Support</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#pooling" data-ice="link">Pooling</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#model" data-ice="link">Model</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#datatypes" data-ice="link">Datatypes</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#hooks" data-ice="link">Hooks</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#sequelize" data-ice="link">Sequelize</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#query-interface" data-ice="link">Query Interface</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#others" data-ice="link">Others</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#dialect-specific" data-ice="link">Dialect Specific</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#mssql" data-ice="link">MSSQL</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#mysql" data-ice="link">MySQL</a></li>
<li data-ice="manualNav" class="indent-h4" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#mariadb" data-ice="link">MariaDB</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#packages" data-ice="link">Packages</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#changelog" data-ice="link">Changelog</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-17" data-ice="link">5.0.0-beta.17</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-16" data-ice="link">5.0.0-beta.16</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-15" data-ice="link">5.0.0-beta.15</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-14" data-ice="link">5.0.0-beta.14</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-13" data-ice="link">5.0.0-beta.13</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-12" data-ice="link">5.0.0-beta.12</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-11" data-ice="link">5.0.0-beta.11</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-10" data-ice="link">5.0.0-beta.10</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-9" data-ice="link">5.0.0-beta.9</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-8" data-ice="link">5.0.0-beta.8</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-7" data-ice="link">5.0.0-beta.7</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-6" data-ice="link">5.0.0-beta.6</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-5" data-ice="link">5.0.0-beta.5</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-4" data-ice="link">5.0.0-beta.4</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-3" data-ice="link">5.0.0-beta.3</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-2" data-ice="link">5.0.0-beta.2</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta-1" data-ice="link">5.0.0-beta.1</a></li>
<li data-ice="manualNav" class="indent-h3" data-link="manual/upgrade-to-v5.html"><a href="/v5/manual/upgrade-to-v5.html#5-0-0-beta" data-ice="link">5.0.0-beta</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/legacy.html"><a href="/v5/manual/legacy.html" data-ice="link">Working with legacy tables</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legacy.html"><a href="/v5/manual/legacy.html#tables" data-ice="link">Tables</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legacy.html"><a href="/v5/manual/legacy.html#fields" data-ice="link">Fields</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legacy.html"><a href="/v5/manual/legacy.html#primary-keys" data-ice="link">Primary keys</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legacy.html"><a href="/v5/manual/legacy.html#foreign-keys" data-ice="link">Foreign keys</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/whos-using.html"><a href="/v5/manual/whos-using.html" data-ice="link">Who's using sequelize?</a></li>
</ul>
  </div>
<div data-ice="manual">
    <ul class="manual-toc">
      
    <li data-ice="manualNav" class="indent-h1" data-link="manual/legal.html"><a href="/v5/manual/legal.html" data-ice="link">Legal Notice</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legal.html"><a href="/v5/manual/legal.html#license" data-ice="link">License</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legal.html"><a href="/v5/manual/legal.html#author-s-" data-ice="link">AUTHOR(S)</a></li>
<li data-ice="manualNav" class="indent-h2" data-link="manual/legal.html"><a href="/v5/manual/legal.html#inhaltliche-verantwortung" data-ice="link">INHALTLICHE VERANTWORTUNG</a></li>
</ul>
  </div>
</div>
</nav>

<div class="content" data-ice="content"><div class="github-markdown">
  <div class="manual-user-index" data-ice="manualUserIndex"><p></p><div>
  <div class="center logo">
    <img src="/v5/manual/asset/logo-small.png" alt="logo">
  </div>
  <div class="center sequelize">Sequelize</div>
</div>

<p></p>
<p><a href="https://www.npmjs.com/package/sequelize"><img src="https://badgen.net/npm/v/sequelize" alt="npm version"></a>
<a href="https://travis-ci.org/sequelize/sequelize"><img src="https://badgen.net/travis/sequelize/sequelize?icon=travis" alt="Travis Build Status"></a>
<a href="https://ci.appveyor.com/project/sushantdhiman/sequelize/branch/master"><img src="https://ci.appveyor.com/api/projects/status/9l1ypgwsp5ij46m3/branch/master?svg=true" alt="Appveyor Build Status"></a>
<a href="https://www.npmjs.com/package/sequelize"><img src="https://badgen.net/npm/dm/sequelize" alt="npm downloads"></a>
<a href="https://codecov.io/gh/sequelize/sequelize"><img src="https://badgen.net/codecov/c/github/sequelize/sequelize?icon=codecov" alt="codecov"></a>
<a href="https://github.com/sequelize/sequelize"><img src="https://badgen.net/github/last-commit/sequelize/sequelize" alt="Last commit"></a>
<a href="https://github.com/sequelize/sequelize"><img src="https://badgen.net/github/merged-prs/sequelize/sequelize" alt="Merged PRs"></a>
<a href="https://github.com/sequelize/sequelize"><img src="https://badgen.net/github/stars/sequelize/sequelize" alt="GitHub stars"></a>
<a href="https://sequelize.org/slack"><img src="https://img.shields.io/badge/Slack-4A154B?logo=slack&logoColor=white" alt="Slack Status"></a>
<a href="https://www.npmjs.com/package/sequelize"><img src="https://badgen.net/npm/node/sequelize" alt="node"></a>
<a href="https://github.com/sequelize/sequelize/blob/master/LICENSE"><img src="https://badgen.net/github/license/sequelize/sequelize" alt="License"></a>
<a href="https://github.com/semantic-release/semantic-release"><img src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg" alt="semantic-release"></a></p>
<p>Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.</p>
<p>Sequelize follows <a href="http://semver.org">SEMVER</a>. Supports Node v6 and above to use ES6 features.</p>
<p><strong>Sequelize v5</strong> was released on March 13, 2019. <a href="/v5/manual/typescript">Official TypeScript typings are now included</a>.</p>
<p>You are currently looking at the <strong>Tutorials and Guides</strong> for Sequelize. You might also be interested in the <a href="/v5/identifiers">API Reference</a>.</p>
<h2 id="quick-example">Quick example</h2><pre><code class="lang-js"><code class="source-code prettyprint">const { Sequelize, Model, DataTypes } = require('sequelize');
const sequelize = new Sequelize('sqlite::memory:');

class User extends Model {}
User.init({
  username: DataTypes.STRING,
  birthday: DataTypes.DATE
}, { sequelize, modelName: 'user' });

sequelize.sync()
  .then(() =&gt; User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
  }))
  .then(jane =&gt; {
    console.log(jane.toJSON());
  });</code>
</code></pre>
<p>To learn more about how to use Sequelize, read the tutorials available in the left menu. Begin with <a href="/v5/manual/getting-started">Getting Started</a>.</p>
</div>

  

  <div class="manual-cards">
    
  <div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Getting started</h1><p>In this tutorial you will learn to make a simple setup of Sequelize to learn the basics.</p><h2>Installing</h2><p>Sequelize is available via <a href="https://www.npmjs.com/package/sequelize">npm</a> (or <a href="https://yarnpkg.com/package/sequelize">yarn</a>).</p><pre><code class="lang-sh"><code class="source-code prettyprint">npm install --save sequelize</code>
</code></pre><p>You'll also have to manually install the driver for your database of choice:</p><pre><code class="lang-sh"><code class="source-code prettyprint"># One of the following:
$ npm install --save pg pg-hstore # Postgres
$ npm install --save mysql2
$ npm install --save mariadb
$ npm install --save sqlite3
$ npm install --save tedious # Microsoft SQL Server</code>
</code></pre><h2>Setting up a connection</h2><p>To connect to the database, you must create a Sequelize instance. This can be done by either passing the connection parameters separately to the Sequelize constructor or by passing a single connection URI:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Sequelize = require('sequelize');

// Option 1: Passing parameters separately
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: /* one of 'mysql' | 'mariadb' | 'postgres' | 'mssql' */
});

// Option 2: Passing a connection URI
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');</code>
</code></pre><p>The Sequelize constructor takes a whole slew of options that are documented in the <a href="/v5/./manual/../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor">API Reference for the Sequelize constructor</a>.</p><h3>Note: setting up SQLite</h3><p>If you're using SQLite, you should use the following instead:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize({
  dialect: 'sqlite',
  storage: 'path/to/database.sqlite'
});</code>
</code></pre><h3>Note: connection pool (production)</h3><p>If you're connecting to the database from a single process, you should create only one Sequelize instance. Sequelize will set up a connection pool on initialization. This connection pool can be configured through the constructor's <code>options</code> parameter (using <code>options.pool</code>), as is shown in the following example:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize(/* ... */, {
  // ...
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});</code>
</code></pre><p>Learn more in the <a href="/v5/./manual/../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor">API Reference for the Sequelize constructor</a>. If you're connecting to the database from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of such that the total maximum size is respected. For example, if you want a max connection pool size of 90 and you have three processes, the Sequelize instance of each process should have a max connection pool size of 30.</p><h3>Testing the connection</h3><p>You can use the <code>.authenticate()</code> function to test if the connection is OK:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize
  .authenticate()
  .then(() =&gt; {
    console.log('Connection has been established successfully.');
  })
  .catch(err =&gt; {
    console.error('Unable to connect to the database:', err);
  });</code>
</code></pre><h3>Closing the connection</h3><p>Sequelize will keep the connection open by default, and use the same connection for all queries. If you need to close the connection, call <code>sequelize.close()</code> (which is asynchronous and returns a Promise).</p><h2>Modeling a table</h2><p>A model is a class that extends <code>Sequelize.Model</code>. Models can be defined in two equivalent ways. The first, with <code>Sequelize.Model.init(attributes, options)</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Model = Sequelize.Model;
class User extends Model {}
User.init({
  // attributes
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  lastName: {
    type: Sequelize.STRING
    // allowNull defaults to true
  }
}, {
  sequelize,
  modelName: 'user'
  // options
});</code>
</code></pre><p>Alternatively, using <code>sequelize.define</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = sequelize.define('user', {
  // attributes
  firstName: {
    type: Sequelize.STRING,
    allowNull: false
  },
  lastName: {
    type: Sequelize.STRING
    // allowNull defaults to true
  }
}, {
  // options
});</code>
</code></pre><p>Internally, <code>sequelize.define</code> calls <code>Model.init</code>.</p><p>The above code tells Sequelize to expect a table named <code>users</code> in the database with the fields <code>firstName</code> and <code>lastName</code>. The table name is automatically pluralized by default (a library called <a href="https://www.npmjs.com/package/inflection">inflection</a> is used under the hood to do this). This behavior can be stopped for a specific model by using the <code>freezeTableName: true</code> option, or for all models by using the <code>define</code> option from the <a href="/v5/./manual/../class/lib/sequelize.js~Sequelize.html#instance-constructor-constructor">Sequelize constructor</a>.</p><p>Sequelize also defines by default the fields <code>id</code> (primary key), <code>createdAt</code> and <code>updatedAt</code> to every model. This behavior can also be changed, of course (check the API Reference to learn more about the available options).</p><h3>Changing the default model options</h3><p>The Sequelize constructor takes a <code>define</code> option which will change the default options for all defined models.</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize(connectionURI, {
  define: {
    // The `timestamps` field specify whether or not the `createdAt` and `updatedAt` fields will be created.
    // This was true by default, but now is false by default
    timestamps: false
  }
});

// Here `timestamps` will be false, so the `createdAt` and `updatedAt` fields will not be created.
class Foo extends Model {}
Foo.init({ /* ... */ }, { sequelize });

// Here `timestamps` is directly set to true, so the `createdAt` and `updatedAt` fields will be created.
class Bar extends Model {}
Bar.init({ /* ... */ }, { sequelize, timestamps: true });</code>
</code></pre><p>You can read more about creating models in the <a href="/v5/./manual/../class/lib/model.js~Model.html#static-method-init">Model.init API Reference</a>, or in the <a href="/v5/./manual/../class/lib/sequelize.js~Sequelize.html#instance-method-define">sequelize.define API reference</a>.</p><h2>Synchronizing the model with the database</h2><p>If you want Sequelize to automatically create the table (or modify it as needed) according to your model definition, you can use the <code>sync</code> method, as follows:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() =&gt; {
  // Now the `users` table in the database corresponds to the model definition
  return User.create({
    firstName: 'John',
    lastName: 'Hancock'
  });
});</code>
</code></pre><h3>Synchronizing all models at once</h3><p>Instead of calling <code>sync()</code> for every model, you can call <code>sequelize.sync()</code> which will automatically sync all models.</p><h3>Note for production</h3><p>In production, you might want to consider using Migrations instead of calling <code>sync()</code> in your code. Learn more in the <a href="/v5/./manual/migrations.html">Migrations</a> guide.</p><h2>Querying</h2><p>A few simple queries are shown below:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Find all users
User.findAll().then(users =&gt; {
  console.log("All users:", JSON.stringify(users, null, 4));
});

// Create a new user
User.create({ firstName: "Jane", lastName: "Doe" }).then(jane =&gt; {
  console.log("Jane's auto-generated ID:", jane.id);
});

// Delete everyone named "Jane"
User.destroy({
  where: {
    firstName: "Jane"
  }
}).then(() =&gt; {
  console.log("Done");
});

// Change everyone without a last name to "Doe"
User.update({ lastName: "Doe" }, {
  where: {
    lastName: null
  }
}).then(() =&gt; {
  console.log("Done");
});</code>
</code></pre><p>Sequelize has a lot of options for querying. You will learn more about those in the next tutorials. It is also possible to make raw SQL queries, if you really need them.</p><h2>Promises and async/await</h2><p>As shown above by the extensive usage of <code>.then</code> calls, Sequelize uses Promises extensively. This means that, if your Node version supports it, you can use ES2017 <code>async/await</code> syntax for all asynchronous calls made with Sequelize.</p><p>Also, all Sequelize promises are in fact <a href="http://bluebirdjs.com">Bluebird</a> promises, so you have the rich Bluebird API to use as well (for example, using <code>finally</code>, <code>tap</code>, <code>tapCatch</code>, <code>map</code>, <code>mapSeries</code>, etc). You can access the Bluebird constructor used internally by Sequelize with <code>Sequelize.Promise</code>, if you want to set any Bluebird specific options.</p></div>
        <a data-ice="link" href="/v5/manual/getting-started.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Dialects</h1><p>Sequelize is independent from specific dialects. This means that you'll have to install the respective connector library to your project yourself.</p><h2>MySQL</h2><p>In order to get Sequelize working nicely together with MySQL, you'll need to install<code>mysql2@^1.5.2</code>or higher. Once that's done you can use it like this:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mysql'
})</code>
</code></pre><p><strong>Note:</strong> You can pass options directly to dialect library by setting the
<code>dialectOptions</code> parameter.</p><h2>MariaDB</h2><p>Library for MariaDB is <code>mariadb</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mariadb',
  dialectOptions: {connectTimeout: 1000} // mariadb connector option
})</code>
</code></pre><p>or using connection String:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('mariadb://user:password@example.com:9821/database')</code>
</code></pre><h2>SQLite</h2><p>For SQLite compatibility you'll need<code>sqlite3@^4.0.0</code>. Configure Sequelize like this:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', {
  // sqlite! now!
  dialect: 'sqlite',

  // the storage engine for sqlite
  // - default ':memory:'
  storage: 'path/to/database.sqlite'
})</code>
</code></pre><p>Or you can use a connection string as well with a path:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('sqlite:/home/abs/path/dbname.db')
const sequelize = new Sequelize('sqlite:relativePath/dbname.db')</code>
</code></pre><h2>PostgreSQL</h2><p>For PostgreSQL, two libraries are needed, <code>pg@^7.0.0</code> and <code>pg-hstore</code>. You'll just need to define the dialect:</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', {
  // gimme postgres, please!
  dialect: 'postgres'
})</code>
</code></pre><p>To connect over a unix domain socket, specify the path to the socket directory
in the <code>host</code> option.</p><p>The socket path must start with <code>/</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', {
  // gimme postgres, please!
  dialect: 'postgres',
  host: '/path/to/socket_directory'
})</code>
</code></pre><h2>MSSQL</h2><p>The library for MSSQL is<code>tedious@^6.0.0</code> You'll just need to define the dialect.
Please note: <code>tedious@^6.0.0</code> requires you to nest MSSQL specific options inside an additional <code>options</code>-object inside the <code>dialectOptions</code>-object.</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', 'username', 'password', {
  dialect: 'mssql',
  dialectOptions: {
    options: {
      useUTC: false,
      dateFirst: 1,
    }
  }
})</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/dialects.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Datatypes</h1><p>Below are some of the datatypes supported by sequelize. For a full and updated list, see <a href="/v5/variable/index.html#static-variable-DataTypes">DataTypes</a>.</p><pre><code class="lang-js"><code class="source-code prettyprint">Sequelize.STRING                      // VARCHAR(255)
Sequelize.STRING(1234)                // VARCHAR(1234)
Sequelize.STRING.BINARY               // VARCHAR BINARY
Sequelize.TEXT                        // TEXT
Sequelize.TEXT('tiny')                // TINYTEXT
Sequelize.CITEXT                      // CITEXT      PostgreSQL and SQLite only.

Sequelize.INTEGER                     // INTEGER
Sequelize.BIGINT                      // BIGINT
Sequelize.BIGINT(11)                  // BIGINT(11)

Sequelize.FLOAT                       // FLOAT
Sequelize.FLOAT(11)                   // FLOAT(11)
Sequelize.FLOAT(11, 10)               // FLOAT(11,10)

Sequelize.REAL                        // REAL        PostgreSQL only.
Sequelize.REAL(11)                    // REAL(11)    PostgreSQL only.
Sequelize.REAL(11, 12)                // REAL(11,12) PostgreSQL only.

Sequelize.DOUBLE                      // DOUBLE
Sequelize.DOUBLE(11)                  // DOUBLE(11)
Sequelize.DOUBLE(11, 10)              // DOUBLE(11,10)

Sequelize.DECIMAL                     // DECIMAL
Sequelize.DECIMAL(10, 2)              // DECIMAL(10,2)

Sequelize.DATE                        // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
Sequelize.DATE(6)                     // DATETIME(6) for mysql 5.6.4+. Fractional seconds support with up to 6 digits of precision
Sequelize.DATEONLY                    // DATE without time.
Sequelize.BOOLEAN                     // TINYINT(1)

Sequelize.ENUM('value 1', 'value 2')  // An ENUM with allowed values 'value 1' and 'value 2'
Sequelize.ARRAY(Sequelize.TEXT)       // Defines an array. PostgreSQL only.
Sequelize.ARRAY(Sequelize.ENUM)       // Defines an array of ENUM. PostgreSQL only.

Sequelize.JSON                        // JSON column. PostgreSQL, SQLite and MySQL only.
Sequelize.JSONB                       // JSONB column. PostgreSQL only.

Sequelize.BLOB                        // BLOB (bytea for PostgreSQL)
Sequelize.BLOB('tiny')                // TINYBLOB (bytea for PostgreSQL. Other options are medium and long)

Sequelize.UUID                        // UUID datatype for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (use defaultValue: Sequelize.UUIDV1 or Sequelize.UUIDV4 to make sequelize generate the ids automatically)

Sequelize.CIDR                        // CIDR datatype for PostgreSQL
Sequelize.INET                        // INET datatype for PostgreSQL
Sequelize.MACADDR                     // MACADDR datatype for PostgreSQL

Sequelize.RANGE(Sequelize.INTEGER)    // Defines int4range range. PostgreSQL only.
Sequelize.RANGE(Sequelize.BIGINT)     // Defined int8range range. PostgreSQL only.
Sequelize.RANGE(Sequelize.DATE)       // Defines tstzrange range. PostgreSQL only.
Sequelize.RANGE(Sequelize.DATEONLY)   // Defines daterange range. PostgreSQL only.
Sequelize.RANGE(Sequelize.DECIMAL)    // Defines numrange range. PostgreSQL only.

Sequelize.ARRAY(Sequelize.RANGE(Sequelize.DATE)) // Defines array of tstzrange ranges. PostgreSQL only.

Sequelize.GEOMETRY                    // Spatial column.  PostgreSQL (with PostGIS) or MySQL only.
Sequelize.GEOMETRY('POINT')           // Spatial column with geometry type. PostgreSQL (with PostGIS) or MySQL only.
Sequelize.GEOMETRY('POINT', 4326)     // Spatial column with geometry type and SRID.  PostgreSQL (with PostGIS) or MySQL only.</code>
</code></pre><p>The BLOB datatype allows you to insert data both as strings and as buffers. When you do a find or findAll on a model which has a BLOB column, that data will always be returned as a buffer.</p><p>If you are working with the PostgreSQL TIMESTAMP WITHOUT TIME ZONE and you need to parse it to a different timezone, please use the pg library's own parser:</p><pre><code class="lang-js"><code class="source-code prettyprint">require('pg').types.setTypeParser(1114, stringValue =&gt; {
  return new Date(stringValue + '+0000');
  // e.g., UTC offset. Use any offset that you would like.
});</code>
</code></pre><p>In addition to the type mentioned above, integer, bigint, float and double also support unsigned and zerofill properties, which can be combined in any order:
Be aware that this does not apply for PostgreSQL!</p><pre><code class="lang-js"><code class="source-code prettyprint">Sequelize.INTEGER.UNSIGNED              // INTEGER UNSIGNED
Sequelize.INTEGER(11).UNSIGNED          // INTEGER(11) UNSIGNED
Sequelize.INTEGER(11).ZEROFILL          // INTEGER(11) ZEROFILL
Sequelize.INTEGER(11).ZEROFILL.UNSIGNED // INTEGER(11) UNSIGNED ZEROFILL
Sequelize.INTEGER(11).UNSIGNED.ZEROFILL // INTEGER(11) UNSIGNED ZEROFILL</code>
</code></pre><p><em>The examples above only show integer, but the same can be done with bigint and float</em></p><p>Usage in object notation:</p><pre><code class="lang-js"><code class="source-code prettyprint">// for enums:
class MyModel extends Model {}
MyModel.init({
  states: {
    type: Sequelize.ENUM,
    values: ['active', 'pending', 'deleted']
  }
}, { sequelize })</code>
</code></pre><h3>Array(ENUM)</h3><p>Its only supported with PostgreSQL.</p><p>Array(Enum) type require special treatment. Whenever Sequelize will talk to database it has to typecast Array values with ENUM name.</p><p>So this enum name must follow this pattern <code>enum_&lt;table_name&gt;_&lt;col_name&gt;</code>. If you are using <code>sync</code> then correct name will automatically be generated.</p><h3>Range types</h3><p>Since range types have extra information for their bound inclusion/exclusion it's not
very straightforward to just use a tuple to represent them in javascript.</p><p>When supplying ranges as values you can choose from the following APIs:</p><pre><code class="lang-js"><code class="source-code prettyprint">// defaults to '["2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")'
// inclusive lower bound, exclusive upper bound
Timeline.create({ range: [new Date(Date.UTC(2016, 0, 1)), new Date(Date.UTC(2016, 1, 1))] });

// control inclusion
const range = [
  { value: new Date(Date.UTC(2016, 0, 1)), inclusive: false },
  { value: new Date(Date.UTC(2016, 1, 1)), inclusive: true },
];
// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]'

// composite form
const range = [
  { value: new Date(Date.UTC(2016, 0, 1)), inclusive: false },
  new Date(Date.UTC(2016, 1, 1)),
];
// '("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00")'

Timeline.create({ range });</code>
</code></pre><p>However, please note that whenever you get back a value that is range you will
receive:</p><pre><code class="lang-js"><code class="source-code prettyprint">// stored value: ("2016-01-01 00:00:00+00:00", "2016-02-01 00:00:00+00:00"]
range // [{ value: Date, inclusive: false }, { value: Date, inclusive: true }]</code>
</code></pre><p>You will need to call reload after updating an instance with a range type or use <code>returning: true</code> option.</p><h4>Special Cases</h4><pre><code class="lang-js"><code class="source-code prettyprint">// empty range:
Timeline.create({ range: [] }); // range = 'empty'

// Unbounded range:
Timeline.create({ range: [null, null] }); // range = '[,)'
// range = '[,"2016-01-01 00:00:00+00:00")'
Timeline.create({ range: [null, new Date(Date.UTC(2016, 0, 1))] });

// Infinite range:
// range = '[-infinity,"2016-01-01 00:00:00+00:00")'
Timeline.create({ range: [-Infinity, new Date(Date.UTC(2016, 0, 1))] });</code>
</code></pre><h2>Extending datatypes</h2><p>Most likely the type you are trying to implement is already included in <a href="/v5/./manual/data-types.html">DataTypes</a>. If a new datatype is not included, this manual will show how to write it yourself.</p><p>Sequelize doesn't create new datatypes in the database. This tutorial explains how to make Sequelize recognize new datatypes and assumes that those new datatypes are already created in the database.</p><p>To extend Sequelize datatypes, do it before any instance is created. This example creates a dummy <code>NEWTYPE</code> that replicates the built-in datatype <code>Sequelize.INTEGER(11).ZEROFILL.UNSIGNED</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">// myproject/lib/sequelize.js

const Sequelize = require('Sequelize');
const sequelizeConfig = require('../config/sequelize')
const sequelizeAdditions = require('./sequelize-additions')

// Function that adds new datatypes
sequelizeAdditions(Sequelize)

// In this exmaple a Sequelize instance is created and exported
const sequelize = new Sequelize(sequelizeConfig)

module.exports = sequelize</code>
</code></pre><pre><code class="lang-js"><code class="source-code prettyprint">// myproject/lib/sequelize-additions.js

module.exports = function sequelizeAdditions(Sequelize) {

  DataTypes = Sequelize.DataTypes

  /*
   * Create new types
   */
  class NEWTYPE extends DataTypes.ABSTRACT {
    // Mandatory, complete definition of the new type in the database
    toSql() {
      return 'INTEGER(11) UNSIGNED ZEROFILL'
    }

    // Optional, validator function
    validate(value, options) {
      return (typeof value === 'number') &amp;&amp; (! Number.isNaN(value))
    }

    // Optional, sanitizer
    _sanitize(value) {
      // Force all numbers to be positive
      if (value &lt; 0) {
        value = 0
      }

      return Math.round(value)
    }

    // Optional, value stringifier before sending to database
    _stringify(value) {
      return value.toString()
    }

    // Optional, parser for values received from the database
    static parse(value) {
      return Number.parseInt(value)
    }
  }

  DataTypes.NEWTYPE = NEWTYPE;

  // Mandatory, set key
  DataTypes.NEWTYPE.prototype.key = DataTypes.NEWTYPE.key = 'NEWTYPE'

  // Optional, disable escaping after stringifier. Not recommended.
  // Warning: disables Sequelize protection against SQL injections
  // DataTypes.NEWTYPE.escape = false

  // For convenience
  // `classToInvokable` allows you to use the datatype without `new`
  Sequelize.NEWTYPE = Sequelize.Utils.classToInvokable(DataTypes.NEWTYPE)

}</code>
</code></pre><p>After creating this new datatype, you need to map this datatype in each database dialect and make some adjustments.</p><h2>PostgreSQL</h2><p>Let's say the name of the new datatype is <code>pg_new_type</code> in the postgres database. That name has to be mapped to <code>DataTypes.NEWTYPE</code>. Additionally, it is required to create a child postgres-specific datatype.</p><pre><code class="lang-js"><code class="source-code prettyprint">// myproject/lib/sequelize-additions.js

module.exports = function sequelizeAdditions(Sequelize) {

  DataTypes = Sequelize.DataTypes

  /*
   * Create new types
   */

  ...

  /*
   * Map new types
   */

  // Mandatory, map postgres datatype name
  DataTypes.NEWTYPE.types.postgres = ['pg_new_type']

  // Mandatory, create a postgres-specific child datatype with its own parse
  // method. The parser will be dynamically mapped to the OID of pg_new_type.
  PgTypes = DataTypes.postgres

  PgTypes.NEWTYPE = function NEWTYPE() {
    if (!(this instanceof PgTypes.NEWTYPE)) return new PgTypes.NEWTYPE();
    DataTypes.NEWTYPE.apply(this, arguments);
  }
  inherits(PgTypes.NEWTYPE, DataTypes.NEWTYPE);

  // Mandatory, create, override or reassign a postgres-specific parser
  //PgTypes.NEWTYPE.parse = value =&gt; value;
  PgTypes.NEWTYPE.parse = DataTypes.NEWTYPE.parse;

  // Optional, add or override methods of the postgres-specific datatype
  // like toSql, escape, validate, _stringify, _sanitize...

}</code>
</code></pre><h3>Ranges</h3><p>After a new range type has been <a href="https://www.postgresql.org/docs/current/static/rangetypes.html#RANGETYPES-DEFINING">defined in postgres</a>, it is trivial to add it to Sequelize.</p><p>In this example the name of the postgres range type is <code>newtype_range</code> and the name of the underlying postgres datatype is <code>pg_new_type</code>. The key of <code>subtypes</code> and <code>castTypes</code> is the key of the Sequelize datatype <code>DataTypes.NEWTYPE.key</code>, in lower case.</p><pre><code class="lang-js"><code class="source-code prettyprint">// myproject/lib/sequelize-additions.js

module.exports = function sequelizeAdditions(Sequelize) {

  DataTypes = Sequelize.DataTypes

  /*
   * Create new types
   */

  ...

  /*
   * Map new types
   */

  ...

  /*
   * Add suport for ranges
   */

  // Add postgresql range, newtype comes from DataType.NEWTYPE.key in lower case
  DataTypes.RANGE.types.postgres.subtypes.newtype = 'newtype_range';
  DataTypes.RANGE.types.postgres.castTypes.newtype = 'pg_new_type';

}</code>
</code></pre><p>The new range can be used in model definitions as <code>Sequelize.RANGE(Sequelize.NEWTYPE)</code> or <code>DataTypes.RANGE(DataTypes.NEWTYPE)</code>.</p></div>
        <a data-ice="link" href="/v5/manual/data-types.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Model definition</h1><p>To define mappings between a model and a table, use the <code>define</code> method. Each column must have a datatype, see more about <a href="/v5/./manual/data-types.html">datatypes</a>.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Project extends Model {}
Project.init({
  title: Sequelize.STRING,
  description: Sequelize.TEXT
}, { sequelize, modelName: 'project' });

class Task extends Model {}
Task.init({
  title: Sequelize.STRING,
  description: Sequelize.TEXT,
  deadline: Sequelize.DATE
}, { sequelize, modelName: 'task' })</code>
</code></pre><p>Apart from <a href="/v5/./manual/data-types.html">datatypes</a>, there are plenty of options that you can set on each column.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Foo extends Model {}
Foo.init({
 // instantiating will automatically set the flag to true if not set
 flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true },

 // default values for dates =&gt; current time
 myDate: { type: Sequelize.DATE, defaultValue: Sequelize.NOW },

 // setting allowNull to false will add NOT NULL to the column, which means an error will be
 // thrown from the DB when the query is executed if the column is null. If you want to check that a value
 // is not null before querying the DB, look at the validations section below.
 title: { type: Sequelize.STRING, allowNull: false },

 // Creating two objects with the same value will throw an error. The unique property can be either a
 // boolean, or a string. If you provide the same string for multiple columns, they will form a
 // composite unique key.
 uniqueOne: { type: Sequelize.STRING,  unique: 'compositeIndex' },
 uniqueTwo: { type: Sequelize.INTEGER, unique: 'compositeIndex' },

 // The unique property is simply a shorthand to create a unique constraint.
 someUnique: { type: Sequelize.STRING, unique: true },

 // It's exactly the same as creating the index in the model's options.
 { someUnique: { type: Sequelize.STRING } },
 { indexes: [ { unique: true, fields: [ 'someUnique' ] } ] },

 // Go on reading for further information about primary keys
 identifier: { type: Sequelize.STRING, primaryKey: true },

 // autoIncrement can be used to create auto_incrementing integer columns
 incrementMe: { type: Sequelize.INTEGER, autoIncrement: true },

 // You can specify a custom column name via the 'field' attribute:
 fieldWithUnderscores: { type: Sequelize.STRING, field: 'field_with_underscores' },

 // It is possible to create foreign keys:
 bar_id: {
   type: Sequelize.INTEGER,

   references: {
     // This is a reference to another model
     model: Bar,

     // This is the column name of the referenced model
     key: 'id',

     // This declares when to check the foreign key constraint. PostgreSQL only.
     deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE
   }
 },

 // It is possible to add comments on columns for MySQL, PostgreSQL and MSSQL only
 commentMe: {
   type: Sequelize.INTEGER,

   comment: 'This is a column name that has a comment'
 }
}, {
  sequelize,
  modelName: 'foo'
});</code>
</code></pre><p>The comment option can also be used on a table, see <a href="/v5/./manual/models-definition.html#configuration">model configuration</a>.</p><h2>Timestamps</h2><p>By default, Sequelize will add the attributes <code>createdAt</code> and <code>updatedAt</code> to your model so you will be able to know when the database entry went into the db and when it was updated last.</p><p>Note that if you are using Sequelize migrations you will need to add the <code>createdAt</code> and <code>updatedAt</code> fields to your migration definition:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
  up(queryInterface, Sequelize) {
    return queryInterface.createTable('my-table', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },

      // Timestamps
      createdAt: Sequelize.DATE,
      updatedAt: Sequelize.DATE,
    })
  },
  down(queryInterface, Sequelize) {
    return queryInterface.dropTable('my-table');
  },
}
</code>
</code></pre><p>If you do not want timestamps on your models, only want some timestamps, or you are working with an existing database where the columns are named something else, jump straight on to <a href="/v5/./manual/models-definition.html#configuration">configuration</a> to see how to do that.</p><h2>Deferrable</h2><p>When you specify a foreign key column it is optionally possible to declare the deferrable
type in PostgreSQL. The following options are available:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Defer all foreign key constraint check to the end of a transaction
Sequelize.Deferrable.INITIALLY_DEFERRED

// Immediately check the foreign key constraints
Sequelize.Deferrable.INITIALLY_IMMEDIATE

// Don't defer the checks at all
Sequelize.Deferrable.NOT</code>
</code></pre><p>The last option is the default in PostgreSQL and won't allow you to dynamically change
the rule in a transaction. See <a href="/v5/./manual/transactions.html#options">the transaction section</a> for further information.</p><h2>Getters &amp; setters</h2><p>It is possible to define 'object-property' getters and setter functions on your models, these can be used both for 'protecting' properties that map to database fields and for defining 'pseudo' properties.</p><p>Getters and Setters can be defined in 2 ways (you can mix and match these 2 approaches):</p><ul>
<li>as part of a single property definition</li>
<li>as part of a model options</li>
</ul><p><strong>N.B:</strong> If a getter or setter is defined in both places then the function found in the relevant property definition will always take precedence.</p><h3>Defining as part of a property</h3><pre><code class="lang-js"><code class="source-code prettyprint">class Employee extends Model {}
Employee.init({
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    get() {
      const title = this.getDataValue('title');
      // 'this' allows you to access attributes of the instance
      return this.getDataValue('name') + ' (' + title + ')';
    },
  },
  title: {
    type: Sequelize.STRING,
    allowNull: false,
    set(val) {
      this.setDataValue('title', val.toUpperCase());
    }
  }
}, { sequelize, modelName: 'employee' });

Employee
  .create({ name: 'John Doe', title: 'senior engineer' })
  .then(employee =&gt; {
    console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
    console.log(employee.get('title')); // SENIOR ENGINEER
  })</code>
</code></pre><h3>Defining as part of the model options</h3><p>Below is an example of defining the getters and setters in the model options.</p><p>The <code>fullName</code> getter, is an example of how you can define pseudo properties on your models - attributes which are not actually part of your database schema. In fact, pseudo properties can be defined in two ways: using model getters, or by using a column with the <a href="/v5/variable/index.html#static-variable-DataTypes"><code>VIRTUAL</code> datatype</a>. Virtual datatypes can have validations, while getters for virtual attributes cannot.</p><p>Note that the <code>this.firstname</code> and <code>this.lastname</code> references in the <code>fullName</code> getter function will trigger a call to the respective getter functions. If you do not want that then use the <code>getDataValue()</code> method to access the raw value (see below).</p><pre><code class="lang-js"><code class="source-code prettyprint">class Foo extends Model {
  get fullName() {
    return this.firstname + ' ' + this.lastname;
  }

  set fullName(value) {
    const names = value.split(' ');
    this.setDataValue('firstname', names.slice(0, -1).join(' '));
    this.setDataValue('lastname', names.slice(-1).join(' '));
  }
}
Foo.init({
  firstname: Sequelize.STRING,
  lastname: Sequelize.STRING
}, {
  sequelize,
  modelName: 'foo'
});

// Or with `sequelize.define`
sequelize.define('Foo', {
  firstname: Sequelize.STRING,
  lastname: Sequelize.STRING
}, {
  getterMethods: {
    fullName() {
      return this.firstname + ' ' + this.lastname;
    }
  },

  setterMethods: {
    fullName(value) {
      const names = value.split(' ');

      this.setDataValue('firstname', names.slice(0, -1).join(' '));
      this.setDataValue('lastname', names.slice(-1).join(' '));
    }
  }
});</code>
</code></pre><h3>Helper functions for use inside getter and setter definitions</h3><ul>
<li>retrieving an underlying property value - always use <code>this.getDataValue()</code></li>
</ul><pre><code class="lang-js"><code class="source-code prettyprint">/* a getter for 'title' property */
get() {
  return this.getDataValue('title')
}</code>
</code></pre><ul>
<li>setting an underlying property value - always use <code>this.setDataValue()</code></li>
</ul><pre><code class="lang-js"><code class="source-code prettyprint">/* a setter for 'title' property */
set(title) {
  this.setDataValue('title', title.toString().toLowerCase());
}</code>
</code></pre><p><strong>N.B:</strong> It is important to stick to using the <code>setDataValue()</code> and <code>getDataValue()</code> functions (as opposed to accessing the underlying "data values" property directly) - doing so protects your custom getters and setters from changes in the underlying model implementations.</p><h2>Validations</h2><p>Model validations allow you to specify format/content/inheritance validations for each attribute of the model.</p><p>Validations are automatically run on <code>create</code>, <code>update</code> and <code>save</code>. You can also call <code>validate()</code> to manually validate an instance.</p><h3>Per-attribute validations</h3><p>You can define your custom validators or use several built-in validators, implemented by <a href="https://github.com/chriso/validator.js">validator.js</a>, as shown below.</p><pre><code class="lang-js"><code class="source-code prettyprint">class ValidateMe extends Model {}
ValidateMe.init({
  bar: {
    type: Sequelize.STRING,
    validate: {
      is: ["^[a-z]+$",'i'],     // will only allow letters
      is: /^[a-z]+$/i,          // same as the previous example using real RegExp
      not: ["[a-z]",'i'],       // will not allow letters
      isEmail: true,            // checks for email format (foo@bar.com)
      isUrl: true,              // checks for url format (http://foo.com)
      isIP: true,               // checks for IPv4 (129.89.23.1) or IPv6 format
      isIPv4: true,             // checks for IPv4 (129.89.23.1)
      isIPv6: true,             // checks for IPv6 format
      isAlpha: true,            // will only allow letters
      isAlphanumeric: true,     // will only allow alphanumeric characters, so "_abc" will fail
      isNumeric: true,          // will only allow numbers
      isInt: true,              // checks for valid integers
      isFloat: true,            // checks for valid floating point numbers
      isDecimal: true,          // checks for any numbers
      isLowercase: true,        // checks for lowercase
      isUppercase: true,        // checks for uppercase
      notNull: true,            // won't allow null
      isNull: true,             // only allows null
      notEmpty: true,           // don't allow empty strings
      equals: 'specific value', // only allow a specific value
      contains: 'foo',          // force specific substrings
      notIn: [['foo', 'bar']],  // check the value is not one of these
      isIn: [['foo', 'bar']],   // check the value is one of these
      notContains: 'bar',       // don't allow specific substrings
      len: [2,10],              // only allow values with length between 2 and 10
      isUUID: 4,                // only allow uuids
      isDate: true,             // only allow date strings
      isAfter: "2011-11-05",    // only allow date strings after a specific date
      isBefore: "2011-11-05",   // only allow date strings before a specific date
      max: 23,                  // only allow values &lt;= 23
      min: 23,                  // only allow values &gt;= 23
      isCreditCard: true,       // check for valid credit card numbers

      // Examples of custom validators:
      isEven(value) {
        if (parseInt(value) % 2 !== 0) {
          throw new Error('Only even values are allowed!');
        }
      }
      isGreaterThanOtherField(value) {
        if (parseInt(value) &lt;= parseInt(this.otherField)) {
          throw new Error('Bar must be greater than otherField.');
        }
      }
    }
  }
}, { sequelize });</code>
</code></pre><p>Note that where multiple arguments need to be passed to the built-in validation functions, the arguments to be passed must be in an array. But if a single array argument is to be passed, for instance an array of acceptable strings for <code>isIn</code>, this will be interpreted as multiple string arguments instead of one array argument. To work around this pass a single-length array of arguments, such as <code>[['one', 'two']]</code> as shown above.</p><p>To use a custom error message instead of that provided by <a href="https://github.com/chriso/validator.js">validator.js</a>, use an object instead of the plain value or array of arguments, for example a validator which needs no argument can be given a custom message with</p><pre><code class="lang-js"><code class="source-code prettyprint">isInt: {
  msg: "Must be an integer number of pennies"
}</code>
</code></pre><p>or if arguments need to also be passed add an <code>args</code> property:</p><pre><code class="lang-js"><code class="source-code prettyprint">isIn: {
  args: [['en', 'zh']],
  msg: "Must be English or Chinese"
}</code>
</code></pre><p>When using custom validator functions the error message will be whatever message the thrown <code>Error</code> object holds.</p><p>See <a href="https://github.com/chriso/validator.js">the validator.js project</a> for more details on the built in validation methods.</p><p><strong>Hint:</strong> You can also define a custom function for the logging part. Just pass a function. The first parameter will be the string that is logged.</p><h3>Per-attribute validators and <code>allowNull</code></h3><p>If a particular field of a model is set to not allow null (with <code>allowNull: false</code>) and that value has been set to <code>null</code>, all validators will be skipped and a <code>ValidationError</code> will be thrown.</p><p>On the other hand, if it is set to allow null (with <code>allowNull: true</code>) and that value has been set to <code>null</code>, only the built-in validators will be skipped, while the custom validators will still run.</p><p>This means you can, for instance, have a string field which validates its length to be between 5 and 10 characters, but which also allows <code>null</code> (since the length validator will be skipped automatically when the value is <code>null</code>):</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({
  username: {
    type: Sequelize.STRING,
    allowNull: true,
    validate: {
      len: [5, 10]
    }
  }
}, { sequelize });</code>
</code></pre><p>You also can conditionally allow <code>null</code> values, with a custom validator, since it won't be skipped:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({
  age: Sequelize.INTEGER,
  name: {
    type: Sequelize.STRING,
    allowNull: true,
    validate: {
      customValidator(value) {
        if (value === null &amp;&amp; this.age !== 10) {
          throw new Error("name can't be null unless age is 10");
        }
      })
    }
  }
}, { sequelize });</code>
</code></pre><p>You can customize <code>allowNull</code> error message by setting the <code>notNull</code> validator:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {
      notNull: {
        msg: 'Please enter your name'
      }
    }
  }
}, { sequelize });</code>
</code></pre><h3>Model-wide validations</h3><p>Validations can also be defined to check the model after the field-specific validators. Using this you could, for example, ensure either neither of <code>latitude</code> and <code>longitude</code> are set or both, and fail if one but not the other is set.</p><p>Model validator methods are called with the model object's context and are deemed to fail if they throw an error, otherwise pass. This is just the same as with custom field-specific validators.</p><p>Any error messages collected are put in the validation result object alongside the field validation errors, with keys named after the failed validation method's key in the <code>validate</code> option object. Even though there can only be one error message for each model validation method at any one time, it is presented as a single string error in an array, to maximize consistency with the field errors.</p><p>An example:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Pub extends Model {}
Pub.init({
  name: { type: Sequelize.STRING },
  address: { type: Sequelize.STRING },
  latitude: {
    type: Sequelize.INTEGER,
    allowNull: true,
    defaultValue: null,
    validate: { min: -90, max: 90 }
  },
  longitude: {
    type: Sequelize.INTEGER,
    allowNull: true,
    defaultValue: null,
    validate: { min: -180, max: 180 }
  },
}, {
  validate: {
    bothCoordsOrNone() {
      if ((this.latitude === null) !== (this.longitude === null)) {
        throw new Error('Require either both latitude and longitude or neither')
      }
    }
  },
  sequelize,
})</code>
</code></pre><p>In this simple case an object fails validation if either latitude or longitude is given, but not both. If we try to build one with an out-of-range latitude and no longitude, <code>raging_bullock_arms.validate()</code> might return</p><pre><code class="lang-js"><code class="source-code prettyprint">{
  'latitude': ['Invalid number: latitude'],
  'bothCoordsOrNone': ['Require either both latitude and longitude or neither']
}</code>
</code></pre><p>Such validation could have also been done with a custom validator defined on a single attribute (such as the <code>latitude</code> attribute, by checking <code>(value === null) !== (this.longitude === null)</code>), but the model-wide validation approach is cleaner.</p><h2>Configuration</h2><p>You can also influence the way Sequelize handles your column names:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Bar extends Model {}
Bar.init({ /* bla */ }, {
  // The name of the model. The model will be stored in `sequelize.models` under this name.
  // This defaults to class name i.e. Bar in this case. This will control name of auto-generated
  // foreignKey and association naming
  modelName: 'bar',

  // don't add the timestamp attributes (updatedAt, createdAt)
  timestamps: false,

  // don't delete database entries but set the newly added attribute deletedAt
  // to the current date (when deletion was done). paranoid will only work if
  // timestamps are enabled
  paranoid: true,

  // Will automatically set field option for all attributes to snake cased name.
  // Does not override attribute with field option already defined
  underscored: true,

  // disable the modification of table names; By default, sequelize will automatically
  // transform all passed model names (first parameter of define) into plural.
  // if you don't want that, set the following
  freezeTableName: true,

  // define the table's name
  tableName: 'my_very_custom_table_name',

  // Enable optimistic locking.  When enabled, sequelize will add a version count attribute
  // to the model and throw an OptimisticLockingError error when stale instances are saved.
  // Set to true or a string with the attribute name you want to use to enable.
  version: true,

  // Sequelize instance
  sequelize,
})</code>
</code></pre><p>If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Foo extends Model {}
Foo.init({ /* bla */ }, {
  // don't forget to enable timestamps!
  timestamps: true,

  // I don't want createdAt
  createdAt: false,

  // I want updatedAt to actually be called updateTimestamp
  updatedAt: 'updateTimestamp',

  // And deletedAt to be called destroyTime (remember to enable paranoid for this to work)
  deletedAt: 'destroyTime',
  paranoid: true,

  sequelize,
})</code>
</code></pre><p>You can also change the database engine, e.g. to MyISAM. InnoDB is the default.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Person extends Model {}
Person.init({ /* attributes */ }, {
  engine: 'MYISAM',
  sequelize
})

// or globally
const sequelize = new Sequelize(db, user, pw, {
  define: { engine: 'MYISAM' }
})</code>
</code></pre><p>Finally you can specify a comment for the table in MySQL and PG</p><pre><code class="lang-js"><code class="source-code prettyprint">class Person extends Model {}
Person.init({ /* attributes */ }, {
  comment: "I'm a table comment!",
  sequelize
})</code>
</code></pre><h2>Import</h2><p>You can also store your model definitions in a single file using the <code>import</code> method. The returned object is exactly the same as defined in the imported file's function. Since <code>v1:5.0</code> of Sequelize the import is cached, so you won't run into troubles when calling the import of a file twice or more often.</p><pre><code class="lang-js"><code class="source-code prettyprint">// in your server file - e.g. app.js
const Project = sequelize.import(__dirname + "/path/to/models/project")

// The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above
module.exports = (sequelize, DataTypes) =&gt; {
  class Project extends sequelize.Model { }
  Project.init({
    name: DataTypes.STRING,
    description: DataTypes.TEXT
  }, { sequelize });
  return Project;
}</code>
</code></pre><p>The <code>import</code> method can also accept a callback as an argument.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.import('project', (sequelize, DataTypes) =&gt; {
  class Project extends sequelize.Model {}
  Project.init({
    name: DataTypes.STRING,
    description: DataTypes.TEXT
  }, { sequelize })
  return Project;
})</code>
</code></pre><p>This extra capability is useful when, for example, <code>Error: Cannot find module</code> is thrown even though <code>/path/to/models/project</code> seems to be correct.  Some frameworks, such as Meteor, overload <code>require</code>, and spit out "surprise" results like :</p><pre><code class="lang-text"><code class="source-code prettyprint">Error: Cannot find module '/home/you/meteorApp/.meteor/local/build/programs/server/app/path/to/models/project.js'</code>
</code></pre><p>This is solved by passing in Meteor's version of <code>require</code>. So, while this probably fails ...</p><pre><code class="lang-js"><code class="source-code prettyprint">const AuthorModel = db.import('./path/to/models/project');</code>
</code></pre><p>... this should succeed ...</p><pre><code class="lang-js"><code class="source-code prettyprint">const AuthorModel = db.import('project', require('./path/to/models/project'));</code>
</code></pre><h2>Optimistic Locking</h2><p>Sequelize has built-in support for optimistic locking through a model instance version count.
Optimistic locking is disabled by default and can be enabled by setting the <code>version</code> property to true in a specific model definition or global model configuration.  See <a href="/v5/./manual/models-definition.html#configuration">model configuration</a> for more details.</p><p>Optimistic locking allows concurrent access to model records for edits and prevents conflicts from overwriting data.  It does this by checking whether another process has made changes to a record since it was read and throws an OptimisticLockError when a conflict is detected.</p><h2>Database synchronization</h2><p>When starting a new project you won't have a database structure and using Sequelize you won't need to. Just specify your model structures and let the library do the rest. Currently supported is the creation and deletion of tables:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Create the tables:
Project.sync()
Task.sync()

// Force the creation!
Project.sync({force: true}) // this will drop the table first and re-create it afterwards

// drop the tables:
Project.drop()
Task.drop()

// event handling:
Project.[sync|drop]().then(() =&gt; {
  // ok ... everything is nice!
}).catch(error =&gt; {
  // oooh, did you enter wrong database credentials?
})</code>
</code></pre><p>Because synchronizing and dropping all of your tables might be a lot of lines to write, you can also let Sequelize do the work for you:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Sync all models that aren't already in the database
sequelize.sync()

// Force sync all models
sequelize.sync({force: true})

// Drop all tables
sequelize.drop()

// emit handling:
sequelize.[sync|drop]().then(() =&gt; {
  // woot woot
}).catch(error =&gt; {
  // whooops
})</code>
</code></pre><p>Because <code>.sync({ force: true })</code> is destructive operation, you can use <code>match</code> option as an additional safety check.
<code>match</code> option tells sequelize to match a regex against the database name before syncing - a safety check for cases
where <code>force: true</code> is used in tests but not live code.</p><pre><code class="lang-js"><code class="source-code prettyprint">// This will run .sync() only if database name ends with '_test'
sequelize.sync({ force: true, match: /_test$/ });</code>
</code></pre><h2>Expansion of models</h2><p>Sequelize Models are ES6 classes. You can very easily add custom instance or class level methods.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {
  // Adding a class level method
  static classLevelMethod() {
    return 'foo';
  }

  // Adding an instance level method
  instanceLevelMethod() {
    return 'bar';
  }
}
User.init({ firstname: Sequelize.STRING }, { sequelize });</code>
</code></pre><p>Of course you can also access the instance's data and generate virtual getters:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {
  getFullname() {
    return [this.firstname, this.lastname].join(' ');
  }
}
User.init({ firstname: Sequelize.STRING, lastname: Sequelize.STRING }, { sequelize });

// Example:
User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'</code>
</code></pre><h3>Indexes</h3><p>Sequelize supports adding indexes to the model definition which will be created during <code>Model.sync()</code> or <code>sequelize.sync</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({}, {
  indexes: [
    // Create a unique index on email
    {
      unique: true,
      fields: ['email']
    },

    // Creates a gin index on data with the jsonb_path_ops operator
    {
      fields: ['data'],
      using: 'gin',
      operator: 'jsonb_path_ops'
    },

    // By default index name will be [table]_[fields]
    // Creates a multi column partial index
    {
      name: 'public_by_author',
      fields: ['author', 'status'],
      where: {
        status: 'public'
      }
    },

    // A BTREE index with an ordered field
    {
      name: 'title_index',
      using: 'BTREE',
      fields: ['author', {attribute: 'title', collate: 'en_US', order: 'DESC', length: 5}]
    }
  ],
  sequelize
});</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/models-definition.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Model usage</h1><h2>Data retrieval / Finders</h2><p>Finder methods are intended to query data from the database. They do <em>not</em> return plain objects but instead return model instances. Because finder methods return model instances you can call any model instance member on the result as described in the documentation for <a href="/v5/./manual/instances.html"><em>instances</em></a>.</p><p>In this document we'll explore what finder methods can do:</p><h3><code>find</code> - Search for one specific element in the database</h3><pre><code class="lang-js"><code class="source-code prettyprint">// search for known ids
Project.findByPk(123).then(project =&gt; {
  // project will be an instance of Project and stores the content of the table entry
  // with id 123. if such an entry is not defined you will get null
})

// search for attributes
Project.findOne({ where: {title: 'aProject'} }).then(project =&gt; {
  // project will be the first entry of the Projects table with the title 'aProject' || null
})


Project.findOne({
  where: {title: 'aProject'},
  attributes: ['id', ['name', 'title']]
}).then(project =&gt; {
  // project will be the first entry of the Projects table with the title 'aProject' || null
  // project.get('title') will contain the name of the project
})</code>
</code></pre><h3><code>findOrCreate</code> - Search for a specific element or create it if not available</h3><p>The method <code>findOrCreate</code> can be used to check if a certain element already exists in the database. If that is the case the method will result in a respective instance. If the element does not yet exist, it will be created.</p><p>Let's assume we have an empty database with a <code>User</code> model which has a <code>username</code> and a <code>job</code>.</p><p><code>where</code> option will be appended to <code>defaults</code> for create case.</p><pre><code class="lang-js"><code class="source-code prettyprint">User
  .findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
  .then(([user, created]) =&gt; {
    console.log(user.get({
      plain: true
    }))
    console.log(created)

    /*
     findOrCreate returns an array containing the object that was found or created and a boolean that
     will be true if a new object was created and false if not, like so:

    [ {
        username: 'sdepold',
        job: 'Technical Lead JavaScript',
        id: 1,
        createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
        updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
      },
      true ]

 In the example above, the array spread on line 3 divides the array into its 2 parts and passes them
  as arguments to the callback function defined beginning at line 39, which treats them as "user" and
  "created" in this case. (So "user" will be the object from index 0 of the returned array and
  "created" will equal "true".)
    */
  })</code>
</code></pre><p>The code created a new instance. So when we already have an instance ...</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({ username: 'fnord', job: 'omnomnom' })
  .then(() =&gt; User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}}))
  .then(([user, created]) =&gt; {
    console.log(user.get({
      plain: true
    }))
    console.log(created)

    /*
    In this example, findOrCreate returns an array like this:
    [ {
        username: 'fnord',
        job: 'omnomnom',
        id: 2,
        createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
        updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
      },
      false
    ]
    The array returned by findOrCreate gets spread into its 2 parts by the array spread on line 3, and
    the parts will be passed as 2 arguments to the callback function beginning on line 69, which will
    then treat them as "user" and "created" in this case. (So "user" will be the object from index 0
    of the returned array and "created" will equal "false".)
    */
  })</code>
</code></pre><p>... the existing entry will not be changed. See the <code>job</code> of the second user, and the fact that created was false.</p><h3><code>findAndCountAll</code> - Search for multiple elements in the database, returns both data and total count</h3><p>This is a convenience method that combines<code>findAll</code> and <code>count</code> (see below) this is useful when dealing with queries related to pagination where you want to retrieve data with a <code>limit</code> and <code>offset</code> but also need to know the total number of records that match the query:</p><p>The success handler will always receive an object with two properties:</p><ul>
<li><code>count</code> - an integer, total number records matching the where clause and other filters due to associations</li>
<li><code>rows</code> - an array of objects, the records matching the where clause and other filters due to associations, within the limit and offset range</li>
</ul><pre><code class="lang-js"><code class="source-code prettyprint">Project
  .findAndCountAll({
     where: {
        title: {
          [Op.like]: 'foo%'
        }
     },
     offset: 10,
     limit: 2
  })
  .then(result =&gt; {
    console.log(result.count);
    console.log(result.rows);
  });</code>
</code></pre><p>It support includes. Only the includes that are marked as <code>required</code> will be added to the count part:</p><p>Suppose you want to find all users who have a profile attached:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAndCountAll({
  include: [
     { model: Profile, required: true }
  ],
  limit: 3
});</code>
</code></pre><p>Because the include for <code>Profile</code> has <code>required</code> set it will result in an inner join, and only the users who have a profile will be counted. If we remove <code>required</code> from the include, both users with and without profiles will be counted. Adding a <code>where</code> clause to the include automatically makes it required:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAndCountAll({
  include: [
     { model: Profile, where: { active: true }}
  ],
  limit: 3
});</code>
</code></pre><p>The query above will only count users who have an active profile, because <code>required</code> is implicitly set to true when you add a where clause to the include.</p><p>The options object that you pass to <code>findAndCountAll</code> is the same as for <code>findAll</code> (described below).</p><h3><code>findAll</code> - Search for multiple elements in the database</h3><pre><code class="lang-js"><code class="source-code prettyprint">// find multiple entries
Project.findAll().then(projects =&gt; {
  // projects will be an array of all Project instances
})

// search for specific attributes - hash usage
Project.findAll({ where: { name: 'A Project' } }).then(projects =&gt; {
  // projects will be an array of Project instances with the specified name
})

// search within a specific range
Project.findAll({ where: { id: [1,2,3] } }).then(projects =&gt; {
  // projects will be an array of Projects having the id 1, 2 or 3
  // this is actually doing an IN query
})

Project.findAll({
  where: {
    id: {
      [Op.and]: {a: 5},           // AND (a = 5)
      [Op.or]: [{a: 5}, {a: 6}],  // (a = 5 OR a = 6)
      [Op.gt]: 6,                // id &gt; 6
      [Op.gte]: 6,               // id &gt;= 6
      [Op.lt]: 10,               // id &lt; 10
      [Op.lte]: 10,              // id &lt;= 10
      [Op.ne]: 20,               // id != 20
      [Op.between]: [6, 10],     // BETWEEN 6 AND 10
      [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
      [Op.in]: [1, 2],           // IN [1, 2]
      [Op.notIn]: [1, 2],        // NOT IN [1, 2]
      [Op.like]: '%hat',         // LIKE '%hat'
      [Op.notLike]: '%hat',       // NOT LIKE '%hat'
      [Op.iLike]: '%hat',         // ILIKE '%hat' (case insensitive)  (PG only)
      [Op.notILike]: '%hat',      // NOT ILIKE '%hat'  (PG only)
      [Op.overlap]: [1, 2],       // &amp;&amp; [1, 2] (PG array overlap operator)
      [Op.contains]: [1, 2],      // @&gt; [1, 2] (PG array contains operator)
      [Op.contained]: [1, 2],     // &lt;@ [1, 2] (PG array contained by operator)
      [Op.any]: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)
    },
    status: {
      [Op.not]: false           // status NOT FALSE
    }
  }
})</code>
</code></pre><h3>Complex filtering / OR / NOT queries</h3><p>It's possible to do complex where queries with multiple levels of nested AND, OR and NOT conditions. In order to do that you can use <code>or</code>, <code>and</code> or <code>not</code> <code>Operators</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.findOne({
  where: {
    name: 'a project',
    [Op.or]: [
      { id: [1,2,3] },
      { id: { [Op.gt]: 10 } }
    ]
  }
})

Project.findOne({
  where: {
    name: 'a project',
    id: {
      [Op.or]: [
        [1,2,3],
        { [Op.gt]: 10 }
      ]
    }
  }
})</code>
</code></pre><p>Both pieces of code will generate the following:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT *
FROM `Projects`
WHERE (
  `Projects`.`name` = 'a project'
   AND (`Projects`.`id` IN (1,2,3) OR `Projects`.`id` &gt; 10)
)
LIMIT 1;</code>
</code></pre><p><code>not</code> example:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.findOne({
  where: {
    name: 'a project',
    [Op.not]: [
      { id: [1,2,3] },
      { array: { [Op.contains]: [3,4,5] } }
    ]
  }
});</code>
</code></pre><p>Will generate:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT *
FROM `Projects`
WHERE (
  `Projects`.`name` = 'a project'
   AND NOT (`Projects`.`id` IN (1,2,3) OR `Projects`.`array` @&gt; ARRAY[3,4,5]::INTEGER[])
)
LIMIT 1;</code>
</code></pre><h3>Manipulating the dataset with limit, offset, order and group</h3><p>To get more relevant data, you can use limit, offset, order and grouping:</p><pre><code class="lang-js"><code class="source-code prettyprint">// limit the results of the query
Project.findAll({ limit: 10 })

// step over the first 10 elements
Project.findAll({ offset: 10 })

// step over the first 10 elements, and take 2
Project.findAll({ offset: 10, limit: 2 })</code>
</code></pre><p>The syntax for grouping and ordering are equal, so below it is only explained with a single example for group, and the rest for order. Everything you see below can also be done for group</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.findAll({order: [['title', 'DESC']]})
// yields ORDER BY title DESC

Project.findAll({group: 'name'})
// yields GROUP BY name</code>
</code></pre><p>Notice how in the two examples above, the string provided is inserted verbatim into the query, i.e. column names are not escaped. When you provide a string to order/group, this will always be the case. If you want to escape column names, you should provide an array of arguments, even though you only want to order/group by a single column</p><pre><code class="lang-js"><code class="source-code prettyprint">something.findOne({
  order: [
    // will return `name`
    ['name'],
    // will return `username` DESC
    ['username', 'DESC'],
    // will return max(`age`)
    sequelize.fn('max', sequelize.col('age')),
    // will return max(`age`) DESC
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],
    // will return otherfunction(`col1`, 12, 'lalala') DESC
    [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
    // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite!
    [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
  ]
})</code>
</code></pre><p>To recap, the elements of the order/group array can be the following:</p><ul>
<li>String - will be quoted</li>
<li>Array - first element will be quoted, second will be appended verbatim</li>
<li>Object -<ul>
<li>Raw will be added verbatim without quoting</li>
<li>Everything else is ignored, and if raw is not set, the query will fail</li>
</ul>
</li>
<li>Sequelize.fn and Sequelize.col returns functions and quoted column names</li>
</ul><h3>Raw queries</h3><p>Sometimes you might be expecting a massive dataset that you just want to display, without manipulation. For each row you select, Sequelize creates an instance with functions for update, delete, get associations etc. If you have thousands of rows, this might take some time. If you only need the raw data and don't want to update anything, you can do like this to get the raw data.</p><pre><code class="lang-js"><code class="source-code prettyprint">// Are you expecting a massive dataset from the DB,
// and don't want to spend the time building DAOs for each entry?
// You can pass an extra query option to get the raw data instead:
Project.findAll({ where: { ... }, raw: true })</code>
</code></pre><h3><code>count</code> - Count the occurrences of elements in the database</h3><p>There is also a method for counting database objects:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.count().then(c =&gt; {
  console.log("There are " + c + " projects!")
})

Project.count({ where: {'id': {[Op.gt]: 25}} }).then(c =&gt; {
  console.log("There are " + c + " projects with an id greater than 25.")
})</code>
</code></pre><h3><code>max</code> - Get the greatest value of a specific attribute within a specific table</h3><p>And here is a method for getting the max value of an attribute</p><pre><code class="lang-js"><code class="source-code prettyprint">/*
  Let's assume 3 person objects with an attribute age.
  The first one is 10 years old,
  the second one is 5 years old,
  the third one is 40 years old.
*/
Project.max('age').then(max =&gt; {
  // this will return 40
})

Project.max('age', { where: { age: { [Op.lt]: 20 } } }).then(max =&gt; {
  // will be 10
})</code>
</code></pre><h3><code>min</code> - Get the least value of a specific attribute within a specific table</h3><p>And here is a method for getting the min value of an attribute:</p><pre><code class="lang-js"><code class="source-code prettyprint">/*
  Let's assume 3 person objects with an attribute age.
  The first one is 10 years old,
  the second one is 5 years old,
  the third one is 40 years old.
*/
Project.min('age').then(min =&gt; {
  // this will return 5
})

Project.min('age', { where: { age: { [Op.gt]: 5 } } }).then(min =&gt; {
  // will be 10
})</code>
</code></pre><h3><code>sum</code> - Sum the value of specific attributes</h3><p>In order to calculate the sum over a specific column of a table, you can
use the <code>sum</code> method.</p><pre><code class="lang-js"><code class="source-code prettyprint">/*
  Let's assume 3 person objects with an attribute age.
  The first one is 10 years old,
  the second one is 5 years old,
  the third one is 40 years old.
*/
Project.sum('age').then(sum =&gt; {
  // this will return 55
})

Project.sum('age', { where: { age: { [Op.gt]: 5 } } }).then(sum =&gt; {
  // will be 50
})</code>
</code></pre><h2>Eager loading</h2><p>When you are retrieving data from the database there is a fair chance that you also want to get associations with the same query - this is called eager loading. The basic idea behind that, is the use of the attribute <code>include</code> when you are calling <code>find</code> or <code>findAll</code>. Lets assume the following setup:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({ name: Sequelize.STRING }, { sequelize, modelName: 'user' })
class Task extends Model {}
Task.init({ name: Sequelize.STRING }, { sequelize, modelName: 'task' })
class Tool extends Model {}
Tool.init({ name: Sequelize.STRING }, { sequelize, modelName: 'tool' })

Task.belongsTo(User)
User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' })

sequelize.sync().then(() =&gt; {
  // this is where we continue ...
})</code>
</code></pre><p>OK. So, first of all, let's load all tasks with their associated user.</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.findAll({ include: [ User ] }).then(tasks =&gt; {
  console.log(JSON.stringify(tasks))

  /*
    [{
      "name": "A Task",
      "id": 1,
      "createdAt": "2013-03-20T20:31:40.000Z",
      "updatedAt": "2013-03-20T20:31:40.000Z",
      "userId": 1,
      "user": {
        "name": "John Doe",
        "id": 1,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z"
      }
    }]
  */
})</code>
</code></pre><p>Notice that the accessor (the <code>User</code> property in the resulting instance) is singular because the association is one-to-something.</p><p>Next thing: Loading of data with many-to-something associations!</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [ Task ] }).then(users =&gt; {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "tasks": [{
        "name": "A Task",
        "id": 1,
        "createdAt": "2013-03-20T20:31:40.000Z",
        "updatedAt": "2013-03-20T20:31:40.000Z",
        "userId": 1
      }]
    }]
  */
})</code>
</code></pre><p>Notice that the accessor (the <code>Tasks</code> property in the resulting instance) is plural because the association is many-to-something.</p><p>If an association is aliased (using the <code>as</code> option), you must specify this alias when including the model. Notice how the user's <code>Tool</code>s are aliased as <code>Instruments</code> above. In order to get that right you have to specify the model you want to load, as well as the alias:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(users =&gt; {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "Instruments": [{
        "name": "Toothpick",
        "id": 1,
        "createdAt": null,
        "updatedAt": null,
        "userId": 1
      }]
    }]
  */
})</code>
</code></pre><p>You can also include by alias name by specifying a string that matches the association alias:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: ['Instruments'] }).then(users =&gt; {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "Instruments": [{
        "name": "Toothpick",
        "id": 1,
        "createdAt": null,
        "updatedAt": null,
        "userId": 1
      }]
    }]
  */
})

User.findAll({ include: [{ association: 'Instruments' }] }).then(users =&gt; {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "Instruments": [{
        "name": "Toothpick",
        "id": 1,
        "createdAt": null,
        "updatedAt": null,
        "userId": 1
      }]
    }]
  */
})</code>
</code></pre><p>When eager loading we can also filter the associated model using <code>where</code>. This will return all <code>User</code>s in which the <code>where</code> clause of <code>Tool</code> model matches rows.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
    include: [{
        model: Tool,
        as: 'Instruments',
        where: { name: { [Op.like]: '%ooth%' } }
    }]
}).then(users =&gt; {
    console.log(JSON.stringify(users))

    /*
      [{
        "name": "John Doe",
        "id": 1,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z",
        "Instruments": [{
          "name": "Toothpick",
          "id": 1,
          "createdAt": null,
          "updatedAt": null,
          "userId": 1
        }]
      }],

      [{
        "name": "John Smith",
        "id": 2,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z",
        "Instruments": [{
          "name": "Toothpick",
          "id": 1,
          "createdAt": null,
          "updatedAt": null,
          "userId": 1
        }]
      }],
    */
  })</code>
</code></pre><p>When an eager loaded model is filtered using <code>include.where</code> then <code>include.required</code> is implicitly set to
<code>true</code>. This means that an inner join is done returning parent models with any matching children.</p><h3>Top level where with eagerly loaded models</h3><p>To move the where conditions from an included model from the <code>ON</code> condition to the top level <code>WHERE</code> you can use the <code>'$nested.column$'</code> syntax:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
    where: {
        '$Instruments.name$': { [Op.iLike]: '%ooth%' }
    },
    include: [{
        model: Tool,
        as: 'Instruments'
    }]
}).then(users =&gt; {
    console.log(JSON.stringify(users));

    /*
      [{
        "name": "John Doe",
        "id": 1,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z",
        "Instruments": [{
          "name": "Toothpick",
          "id": 1,
          "createdAt": null,
          "updatedAt": null,
          "userId": 1
        }]
      }],

      [{
        "name": "John Smith",
        "id": 2,
        "createdAt": "2013-03-20T20:31:45.000Z",
        "updatedAt": "2013-03-20T20:31:45.000Z",
        "Instruments": [{
          "name": "Toothpick",
          "id": 1,
          "createdAt": null,
          "updatedAt": null,
          "userId": 1
        }]
      }],
    */</code>
</code></pre><h3>Including everything</h3><p>To include all attributes, you can pass a single object with <code>all: true</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ all: true }]});</code>
</code></pre><h3>Including soft deleted records</h3><p>In case you want to eager load soft deleted records you can do that by setting <code>include.paranoid</code> to <code>false</code></p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
    include: [{
        model: Tool,
        where: { name: { [Op.like]: '%ooth%' } },
        paranoid: false // query and loads the soft deleted records
    }]
});</code>
</code></pre><h3>Ordering Eager Loaded Associations</h3><p>In the case of a one-to-many relationship.</p><pre><code class="lang-js"><code class="source-code prettyprint">Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] });
Company.findAll({ include: [ Division ], order: [ [ Division, 'name', 'DESC' ] ] });
Company.findAll({
  include: [ { model: Division, as: 'Div' } ],
  order: [ [ { model: Division, as: 'Div' }, 'name' ] ]
});
Company.findAll({
  include: [ { model: Division, as: 'Div' } ],
  order: [ [ { model: Division, as: 'Div' }, 'name', 'DESC' ] ]
});
Company.findAll({
  include: [ { model: Division, include: [ Department ] } ],
  order: [ [ Division, Department, 'name' ] ]
});</code>
</code></pre><p>In the case of many-to-many joins, you are also able to sort by attributes in the through table.</p><pre><code class="lang-js"><code class="source-code prettyprint">Company.findAll({
  include: [ { model: Division, include: [ Department ] } ],
  order: [ [ Division, DepartmentDivision, 'name' ] ]
});</code>
</code></pre><h3>Nested eager loading</h3><p>You can use nested eager loading to load all related models of a related model:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
  include: [
    {model: Tool, as: 'Instruments', include: [
      {model: Teacher, include: [ /* etc */]}
    ]}
  ]
}).then(users =&gt; {
  console.log(JSON.stringify(users))

  /*
    [{
      "name": "John Doe",
      "id": 1,
      "createdAt": "2013-03-20T20:31:45.000Z",
      "updatedAt": "2013-03-20T20:31:45.000Z",
      "Instruments": [{ // 1:M and N:M association
        "name": "Toothpick",
        "id": 1,
        "createdAt": null,
        "updatedAt": null,
        "userId": 1,
        "Teacher": { // 1:1 association
          "name": "Jimi Hendrix"
        }
      }]
    }]
  */
})</code>
</code></pre><p>This will produce an outer join. However, a <code>where</code> clause on a related model will create an inner join and return only the instances that have matching sub-models. To return all parent instances, you should add <code>required: false</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
  include: [{
    model: Tool,
    as: 'Instruments',
    include: [{
      model: Teacher,
      where: {
        school: "Woodstock Music School"
      },
      required: false
    }]
  }]
}).then(users =&gt; {
  /* ... */
})</code>
</code></pre><p>The query above will return all users, and all their instruments, but only those teachers associated with <code>Woodstock Music School</code>.</p><p>Include all also supports nested loading:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({ include: [{ all: true, nested: true }]});</code>
</code></pre><h3>Use right join for association</h3><p>By default, associations are loaded using a left join, that is to say it only includes records from the parent table. You can change this behavior to a right join by passing the <code>right</code> property, if the dialect you are using supports it. Currently, <code>sqlite</code> <em>does not</em> support <a href="https://www.sqlite.org/omitted.html">right joins</a>.</p><p><em>Note:</em> <code>right</code> is only respected if <code>required</code> is false.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
    include: [{
        model: Tool // will create a left join
    }]
});

User.findAll({
    include: [{
        model: Tool,
        right: true // will create a right join
    }]
});

User.findAll({
    include: [{
        model: Tool,
        required: true,
        right: true // has no effect, will create an inner join
    }]
});

User.findAll({
    include: [{
        model: Tool,
        where: { name: { [Op.like]: '%ooth%' } },
        right: true // has no effect, will create an inner join
    }]
});

User.findAll({
    include: [{
        model: Tool,
        where: { name: { [Op.like]: '%ooth%' } },
        required: false
        right: true // because we set `required` to false, this will create a right join
    }]
});</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/models-usage.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Hooks</h1><p>Hooks (also known as lifecycle events), are functions which are called before and after calls in sequelize are executed. For example, if you want to always set a value on a model before saving it, you can add a <code>beforeUpdate</code> hook.</p><p><strong>Note:</strong> <em>You can't use hooks with instances. Hooks are used with models.</em></p><p>For a full list of hooks, see <a href="https://github.com/sequelize/sequelize/blob/master/lib/hooks.js#L7">Hooks file</a>.</p><h2>Order of Operations</h2><pre><code class="lang-text"><code class="source-code prettyprint">(1)
  beforeBulkCreate(instances, options)
  beforeBulkDestroy(options)
  beforeBulkUpdate(options)
(2)
  beforeValidate(instance, options)
(-)
  validate
(3)
  afterValidate(instance, options)
  - or -
  validationFailed(instance, options, error)
(4)
  beforeCreate(instance, options)
  beforeDestroy(instance, options)
  beforeUpdate(instance, options)
  beforeSave(instance, options)
  beforeUpsert(values, options)
(-)
  create
  destroy
  update
(5)
  afterCreate(instance, options)
  afterDestroy(instance, options)
  afterUpdate(instance, options)
  afterSave(instance, options)
  afterUpsert(created, options)
(6)
  afterBulkCreate(instances, options)
  afterBulkDestroy(options)
  afterBulkUpdate(options)</code>
</code></pre><h2>Declaring Hooks</h2><p>Arguments to hooks are passed by reference. This means, that you can change the values, and this will be reflected in the insert / update statement. A hook may contain async actions - in this case the hook function should return a promise.</p><p>There are currently three ways to programmatically add hooks:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Method 1 via the .init() method
class User extends Model {}
User.init({
  username: DataTypes.STRING,
  mood: {
    type: DataTypes.ENUM,
    values: ['happy', 'sad', 'neutral']
  }
}, {
  hooks: {
    beforeValidate: (user, options) =&gt; {
      user.mood = 'happy';
    },
    afterValidate: (user, options) =&gt; {
      user.username = 'Toni';
    }
  },
  sequelize
});

// Method 2 via the .addHook() method
User.addHook('beforeValidate', (user, options) =&gt; {
  user.mood = 'happy';
});

User.addHook('afterValidate', 'someCustomName', (user, options) =&gt; {
  return Promise.reject(new Error("I'm afraid I can't let you do that!"));
});

// Method 3 via the direct method
User.beforeCreate((user, options) =&gt; {
  return hashPassword(user.password).then(hashedPw =&gt; {
    user.password = hashedPw;
  });
});

User.afterValidate('myHookAfter', (user, options) =&gt; {
  user.username = 'Toni';
});</code>
</code></pre><h2>Removing hooks</h2><p>Only a hook with name param can be removed.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Book extends Model {}
Book.init({
  title: DataTypes.STRING
}, { sequelize });

Book.addHook('afterCreate', 'notifyUsers', (book, options) =&gt; {
  // ...
});

Book.removeHook('afterCreate', 'notifyUsers');</code>
</code></pre><p>You can have many hooks with same name. Calling <code>.removeHook()</code> will remove all of them.</p><h2>Global / universal hooks</h2><p>Global hooks are hooks which are run for all models. They can define behaviours that you want for all your models, and are especially useful for plugins. They can be defined in two ways, which have slightly different semantics:</p><h3>Default Hooks (Sequelize.options.define)</h3><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize(..., {
    define: {
        hooks: {
            beforeCreate: () =&gt; {
              // Do stuff
            }
        }
    }
});</code>
</code></pre><p>This adds a default hook to all models, which is run if the model does not define its own <code>beforeCreate</code> hook:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({}, { sequelize });
class Project extends Model {}
Project.init({}, {
    hooks: {
        beforeCreate: () =&gt; {
            // Do other stuff
        }
    },
    sequelize
});

User.create() // Runs the global hook
Project.create() // Runs its own hook (because the global hook is overwritten)</code>
</code></pre><h3>Permanent Hooks (Sequelize.addHook)</h3><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.addHook('beforeCreate', () =&gt; {
    // Do stuff
});</code>
</code></pre><p>This hook is always run before create, regardless of whether the model specifies its own <code>beforeCreate</code> hook. Local hooks are always run before global hooks:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({}, { sequelize });
class Project extends Model {}
Project.init({}, {
    hooks: {
        beforeCreate: () =&gt; {
            // Do other stuff
        }
    },
    sequelize
});

User.create() // Runs the global hook
Project.create() // Runs its own hook, followed by the global hook</code>
</code></pre><p>Permanent hooks may also be defined in <code>Sequelize.options</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">new Sequelize(..., {
    hooks: {
        beforeCreate: () =&gt; {
            // do stuff
        }
    }
});</code>
</code></pre><h3>Connection Hooks</h3><p>Sequelize provides four hooks that are executed immediately before and after a database connection is obtained or released:</p><pre><code class="lang-text"><code class="source-code prettyprint">beforeConnect(config)
afterConnect(connection, config)
beforeDisconnect(connection)
afterDisconnect(connection)</code>
</code></pre><p>These hooks can be useful if you need to asynchronously obtain database credentials, or need to directly access the low-level database connection after it has been created.</p><p>For example, we can asynchronously obtain a database password from a rotating token store, and mutate Sequelize's configuration object with the new credentials:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.beforeConnect((config) =&gt; {
    return getAuthToken()
        .then((token) =&gt; {
             config.password = token;
         });
    });</code>
</code></pre><p>These hooks may <em>only</em> be declared as a permanent global hook, as the connection pool is shared by all models.</p><h2>Instance hooks</h2><p>The following hooks will emit whenever you're editing a single object</p><pre><code class="lang-text"><code class="source-code prettyprint">beforeValidate
afterValidate or validationFailed
beforeCreate / beforeUpdate / beforeSave  / beforeDestroy
afterCreate / afterUpdate / afterSave / afterDestroy</code>
</code></pre><pre><code class="lang-js"><code class="source-code prettyprint">// ...define ...
User.beforeCreate(user =&gt; {
  if (user.accessLevel &gt; 10 &amp;&amp; user.username !== "Boss") {
    throw new Error("You can't grant this user an access level above 10!")
  }
})</code>
</code></pre><p>This example will return an error:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({username: 'Not a Boss', accessLevel: 20}).catch(err =&gt; {
  console.log(err); // You can't grant this user an access level above 10!
});</code>
</code></pre><p>The following example would return successful:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({username: 'Boss', accessLevel: 20}).then(user =&gt; {
  console.log(user); // user object with username as Boss and accessLevel of 20
});</code>
</code></pre><h3>Model hooks</h3><p>Sometimes you'll be editing more than one record at a time by utilizing the <code>bulkCreate, update, destroy</code> methods on the model. The following will emit whenever you're using one of those methods:</p><pre><code class="lang-text"><code class="source-code prettyprint">beforeBulkCreate(instances, options)
beforeBulkUpdate(options)
beforeBulkDestroy(options)
afterBulkCreate(instances, options)
afterBulkUpdate(options)
afterBulkDestroy(options)</code>
</code></pre><p>If you want to emit hooks for each individual record, along with the bulk hooks you can pass <code>individualHooks: true</code> to the call.</p><p><strong>WARNING</strong>: if you use individual hooks, <em>all instances that are updated or destroyed will get loaded into memory</em> before your hooks are called.  The number of instances Sequelize can handle with individual hooks is limited by available memory.</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.destroy({ where: {accessLevel: 0}, individualHooks: true});
// Will select all records that are about to be deleted and emit before- + after- Destroy on each instance

Model.update({username: 'Toni'}, { where: {accessLevel: 0}, individualHooks: true});
// Will select all records that are about to be updated and emit before- + after- Update on each instance</code>
</code></pre><p>The <code>options</code> argument of hook method would be the second argument provided to the corresponding method or its
cloned and extended version.</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.beforeBulkCreate((records, {fields}) =&gt; {
  // records = the first argument sent to .bulkCreate
  // fields = one of the second argument fields sent to .bulkCreate
})

Model.bulkCreate([
    {username: 'Toni'}, // part of records argument
    {username: 'Tobi'} // part of records argument
  ], {fields: ['username']} // options parameter
)

Model.beforeBulkUpdate(({attributes, where}) =&gt; {
  // where - in one of the fields of the clone of second argument sent to .update
  // attributes - is one of the fields that the clone of second argument of .update would be extended with
})

Model.update({gender: 'Male'} /*attributes argument*/, { where: {username: 'Tom'}} /*where argument*/)

Model.beforeBulkDestroy(({where, individualHooks}) =&gt; {
  // individualHooks - default of overridden value of extended clone of second argument sent to Model.destroy
  // where - in one of the fields of the clone of second argument sent to Model.destroy
})

Model.destroy({ where: {username: 'Tom'}} /*where argument*/)</code>
</code></pre><p>If you use <code>Model.bulkCreate(...)</code> with the <code>updateOnDuplicate</code> option, changes made in the hook to fields that aren't given in the <code>updateOnDuplicate</code> array will not be persisted to the database. However it is possible to change the updateOnDuplicate option inside the hook if this is what you want.</p><pre><code class="lang-js"><code class="source-code prettyprint">// Bulk updating existing users with updateOnDuplicate option
Users.bulkCreate([
  { id: 1, isMember: true },
  { id: 2, isMember: false }
], {
  updateOnDuplicate: ['isMember']
});

User.beforeBulkCreate((users, options) =&gt; {
  for (const user of users) {
    if (user.isMember) {
      user.memberSince = new Date();
    }
  }

  // Add memberSince to updateOnDuplicate otherwise the memberSince date wont be
  // saved to the database
  options.updateOnDuplicate.push('memberSince');
});</code>
</code></pre><h2>Associations</h2><p>For the most part hooks will work the same for instances when being associated except a few things</p><ol>
<li>When using add/set functions the beforeUpdate/afterUpdate hooks will run.</li>
<li>The only way to call beforeDestroy/afterDestroy hooks are on associations with <code>onDelete: 'cascade'</code> and the option <code>hooks: true</code>. For instance:</li>
</ol><pre><code class="lang-js"><code class="source-code prettyprint">class Projects extends Model {}
Projects.init({
  title: DataTypes.STRING
}, { sequelize });

class Tasks extends Model {}
Tasks.init({
  title: DataTypes.STRING
}, { sequelize });

Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true });
Tasks.belongsTo(Projects);</code>
</code></pre><p>This code will run beforeDestroy/afterDestroy on the Tasks table. Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute a</p><pre><code class="lang-sql"><code class="source-code prettyprint">DELETE FROM `table` WHERE associatedIdentifier = associatedIdentifier.primaryKey</code>
</code></pre><p>However, adding <code>hooks: true</code> explicitly tells Sequelize that optimization is not of your concern and will perform a <code>SELECT</code> on the associated objects and destroy each instance one by one in order to be able to call the hooks with the right parameters.</p><p>If your association is of type <code>n:m</code>, you may be interested in firing hooks on the through model when using the <code>remove</code> call. Internally, sequelize is using <code>Model.destroy</code> resulting in calling the <code>bulkDestroy</code> instead of the <code>before/afterDestroy</code> hooks on each through instance.</p><p>This can be simply solved by passing <code>{individualHooks: true}</code> to the <code>remove</code> call, resulting on each hook to be called on each removed through instance object.</p><h2>A Note About Transactions</h2><p>Note that many model operations in Sequelize allow you to specify a transaction in the options parameter of the method. If a transaction _is_ specified in the original call, it will be present in the options parameter passed to the hook function. For example, consider the following snippet:</p><pre><code class="lang-js"><code class="source-code prettyprint">// Here we use the promise-style of async hooks rather than
// the callback.
User.addHook('afterCreate', (user, options) =&gt; {
  // 'transaction' will be available in options.transaction

  // This operation will be part of the same transaction as the
  // original User.create call.
  return User.update({
    mood: 'sad'
  }, {
    where: {
      id: user.id
    },
    transaction: options.transaction
  });
});


sequelize.transaction(transaction =&gt; {
  User.create({
    username: 'someguy',
    mood: 'happy',
    transaction
  });
});</code>
</code></pre><p>If we had not included the transaction option in our call to <code>User.update</code> in the preceding code, no change would have occurred, since our newly created user does not exist in the database until the pending transaction has been committed.</p><h3>Internal Transactions</h3><p>It is very important to recognize that sequelize may make use of transactions internally for certain operations such as <code>Model.findOrCreate</code>. If your hook functions execute read or write operations that rely on the object's presence in the database, or modify the object's stored values like the example in the preceding section, you should always specify <code>{ transaction: options.transaction }</code>.</p><p>If the hook has been called in the process of a transacted operation, this makes sure that your dependent read/write is a part of that same transaction. If the hook is not transacted, you have simply specified <code>{ transaction: null }</code> and can expect the default behaviour.</p></div>
        <a data-ice="link" href="/v5/manual/hooks.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Querying</h1><h2>Attributes</h2><p>To select only some attributes, you can use the <code>attributes</code> option. Most often, you pass an array:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({
  attributes: ['foo', 'bar']
});</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT foo, bar ...</code>
</code></pre><p>Attributes can be renamed using a nested array:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({
  attributes: ['foo', ['bar', 'baz']]
});</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT foo, bar AS baz ...</code>
</code></pre><p>You can use <code>sequelize.fn</code> to do aggregations:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({
  attributes: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
});</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT COUNT(hats) AS no_hats ...</code>
</code></pre><p>When using aggregation function, you must give it an alias to be able to access it from the model. In the example above you can get the number of hats with <code>instance.get('no_hats')</code>.</p><p>Sometimes it may be tiresome to list all the attributes of the model if you only want to add an aggregation:</p><pre><code class="lang-js"><code class="source-code prettyprint">// This is a tiresome way of getting the number of hats...
Model.findAll({
  attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']]
});

// This is shorter, and less error prone because it still works if you add / remove attributes
Model.findAll({
  attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }
});</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT id, foo, bar, baz, quz, COUNT(hats) AS no_hats ...</code>
</code></pre><p>Similarly, it's also possible to remove a selected few attributes:</p><pre><code class="lang-js"><code class="source-code prettyprint">Model.findAll({
  attributes: { exclude: ['baz'] }
});</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT id, foo, bar, quz ...</code>
</code></pre><h2>Where</h2><p>Whether you are querying with findAll/find or doing bulk updates/destroys you can pass a <code>where</code> object to filter the query.</p><p><code>where</code> generally takes an object from attribute:value pairs, where value can be primitives for equality matches or keyed objects for other operators.</p><p>It's also possible to generate complex AND/OR conditions by nesting sets of <code>or</code> and <code>and</code> <code>Operators</code>.</p><h3>Basics</h3><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op;

Post.findAll({
  where: {
    authorId: 2
  }
});
// SELECT * FROM post WHERE authorId = 2

Post.findAll({
  where: {
    authorId: 12,
    status: 'active'
  }
});
// SELECT * FROM post WHERE authorId = 12 AND status = 'active';

Post.findAll({
  where: {
    [Op.or]: [{authorId: 12}, {authorId: 13}]
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.findAll({
  where: {
    authorId: {
      [Op.or]: [12, 13]
    }
  }
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Post.destroy({
  where: {
    status: 'inactive'
  }
});
// DELETE FROM post WHERE status = 'inactive';

Post.update({
  updatedAt: null,
}, {
  where: {
    deletedAt: {
      [Op.ne]: null
    }
  }
});
// UPDATE post SET updatedAt = null WHERE deletedAt NOT NULL;

Post.findAll({
  where: sequelize.where(sequelize.fn('char_length', sequelize.col('status')), 6)
});
// SELECT * FROM post WHERE char_length(status) = 6;</code>
</code></pre><h3>Operators</h3><p>Sequelize exposes symbol operators that can be used for to create more complex comparisons -</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op

[Op.and]: [{a: 5}, {b: 6}] // (a = 5) AND (b = 6)
[Op.or]: [{a: 5}, {a: 6}]  // (a = 5 OR a = 6)
[Op.gt]: 6,                // &gt; 6
[Op.gte]: 6,               // &gt;= 6
[Op.lt]: 10,               // &lt; 10
[Op.lte]: 10,              // &lt;= 10
[Op.ne]: 20,               // != 20
[Op.eq]: 3,                // = 3
[Op.is]: null              // IS NULL
[Op.not]: true,            // IS NOT TRUE
[Op.between]: [6, 10],     // BETWEEN 6 AND 10
[Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
[Op.in]: [1, 2],           // IN [1, 2]
[Op.notIn]: [1, 2],        // NOT IN [1, 2]
[Op.like]: '%hat',         // LIKE '%hat'
[Op.notLike]: '%hat'       // NOT LIKE '%hat'
[Op.iLike]: '%hat'         // ILIKE '%hat' (case insensitive) (PG only)
[Op.notILike]: '%hat'      // NOT ILIKE '%hat'  (PG only)
[Op.startsWith]: 'hat'     // LIKE 'hat%'
[Op.endsWith]: 'hat'       // LIKE '%hat'
[Op.substring]: 'hat'      // LIKE '%hat%'
[Op.regexp]: '^[h|a|t]'    // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
[Op.notRegexp]: '^[h|a|t]' // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
[Op.iRegexp]: '^[h|a|t]'    // ~* '^[h|a|t]' (PG only)
[Op.notIRegexp]: '^[h|a|t]' // !~* '^[h|a|t]' (PG only)
[Op.like]: { [Op.any]: ['cat', 'hat']}
                           // LIKE ANY ARRAY['cat', 'hat'] - also works for iLike and notLike
[Op.overlap]: [1, 2]       // &amp;&amp; [1, 2] (PG array overlap operator)
[Op.contains]: [1, 2]      // @&gt; [1, 2] (PG array contains operator)
[Op.contained]: [1, 2]     // &lt;@ [1, 2] (PG array contained by operator)
[Op.any]: [2,3]            // ANY ARRAY[2, 3]::INTEGER (PG only)

[Op.col]: 'user.organization_id' // = "user"."organization_id", with dialect specific column identifiers, PG in this example
[Op.gt]: { [Op.all]: literal('SELECT 1') }
                          // &gt; ALL (SELECT 1)</code>
</code></pre><h4>Range Operators</h4><p>Range types can be queried with all supported operators.</p><p>Keep in mind, the provided range value can
<a href="/v5/./manual/data-types.html#range-types">define the bound inclusion/exclusion</a>
as well.</p><pre><code class="lang-js"><code class="source-code prettyprint">// All the above equality and inequality operators plus the following:

[Op.contains]: 2           // @&gt; '2'::integer (PG range contains element operator)
[Op.contains]: [1, 2]      // @&gt; [1, 2) (PG range contains range operator)
[Op.contained]: [1, 2]     // &lt;@ [1, 2) (PG range is contained by operator)
[Op.overlap]: [1, 2]       // &amp;&amp; [1, 2) (PG range overlap (have points in common) operator)
[Op.adjacent]: [1, 2]      // -|- [1, 2) (PG range is adjacent to operator)
[Op.strictLeft]: [1, 2]    // &lt;&lt; [1, 2) (PG range strictly left of operator)
[Op.strictRight]: [1, 2]   // &gt;&gt; [1, 2) (PG range strictly right of operator)
[Op.noExtendRight]: [1, 2] // &amp;&lt; [1, 2) (PG range does not extend to the right of operator)
[Op.noExtendLeft]: [1, 2]  // &amp;&gt; [1, 2) (PG range does not extend to the left of operator)</code>
</code></pre><h4>Combinations</h4><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op;

{
  rank: {
    [Op.or]: {
      [Op.lt]: 1000,
      [Op.eq]: null
    }
  }
}
// rank &lt; 1000 OR rank IS NULL

{
  createdAt: {
    [Op.lt]: new Date(),
    [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
  }
}
// createdAt &lt; [timestamp] AND createdAt &gt; [timestamp]

{
  [Op.or]: [
    {
      title: {
        [Op.like]: 'Boat%'
      }
    },
    {
      description: {
        [Op.like]: '%boat%'
      }
    }
  ]
}
// title LIKE 'Boat%' OR description LIKE '%boat%'</code>
</code></pre><h4>Operators Aliases</h4><p>Sequelize allows setting specific strings as aliases for operators. With v5 this will give you deprecation warning.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op;
const operatorsAliases = {
  $gt: Op.gt
}
const connection = new Sequelize(db, user, pass, { operatorsAliases })

[Op.gt]: 6 // &gt; 6
$gt: 6 // same as using Op.gt (&gt; 6)</code>
</code></pre><h4>Operators security</h4><p>By default Sequelize will use Symbol operators. Using Sequelize without any aliases improves security. Not having any string aliases will make it extremely unlikely that operators could be injected but you should always properly validate and sanitize user input.</p><p>Some frameworks automatically parse user input into js objects and if you fail to sanitize your input it might be possible to inject an Object with string operators to Sequelize.</p><p>For better security it is highly advised to use symbol operators from <code>Sequelize.Op</code> like <code>Op.and</code> / <code>Op.or</code> in your code and not depend on any string based operators like <code>$and</code> / <code>$or</code> at all. You can limit alias your application will need by setting <code>operatorsAliases</code> option, remember to sanitize user input especially when you are directly passing them to Sequelize methods.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op;

//use sequelize without any operators aliases
const connection = new Sequelize(db, user, pass, { operatorsAliases: false });

//use sequelize with only alias for $and =&gt; Op.and
const connection2 = new Sequelize(db, user, pass, { operatorsAliases: { $and: Op.and } });</code>
</code></pre><p>Sequelize will warn you if you're using the default aliases and not limiting them
if you want to keep using all default aliases (excluding legacy ones) without the warning you can pass the following operatorsAliases option -</p><pre><code class="lang-js"><code class="source-code prettyprint">const Op = Sequelize.Op;
const operatorsAliases = {
  $eq: Op.eq,
  $ne: Op.ne,
  $gte: Op.gte,
  $gt: Op.gt,
  $lte: Op.lte,
  $lt: Op.lt,
  $not: Op.not,
  $in: Op.in,
  $notIn: Op.notIn,
  $is: Op.is,
  $like: Op.like,
  $notLike: Op.notLike,
  $iLike: Op.iLike,
  $notILike: Op.notILike,
  $regexp: Op.regexp,
  $notRegexp: Op.notRegexp,
  $iRegexp: Op.iRegexp,
  $notIRegexp: Op.notIRegexp,
  $between: Op.between,
  $notBetween: Op.notBetween,
  $overlap: Op.overlap,
  $contains: Op.contains,
  $contained: Op.contained,
  $adjacent: Op.adjacent,
  $strictLeft: Op.strictLeft,
  $strictRight: Op.strictRight,
  $noExtendRight: Op.noExtendRight,
  $noExtendLeft: Op.noExtendLeft,
  $and: Op.and,
  $or: Op.or,
  $any: Op.any,
  $all: Op.all,
  $values: Op.values,
  $col: Op.col
};

const connection = new Sequelize(db, user, pass, { operatorsAliases });</code>
</code></pre><h3>JSON</h3><p>The JSON data type is supported by the PostgreSQL, SQLite, MySQL and MariaDB dialects only.</p><h4>PostgreSQL</h4><p>The JSON data type in PostgreSQL stores the value as plain text, as opposed to binary representation. If you simply want to store and retrieve a JSON representation, using JSON will take less disk space and less time to build from its input representation. However, if you want to do any operations on the JSON value, you should prefer the JSONB data type described below.</p><h4>MSSQL</h4><p>MSSQL does not have a JSON data type, however it does provide support for JSON stored as strings through certain functions since SQL Server 2016. Using these functions, you will be able to query the JSON stored in the string, but any returned values will need to be parsed separately.</p><pre><code class="lang-js"><code class="source-code prettyprint">// ISJSON - to test if a string contains valid JSON
User.findAll({
  where: sequelize.where(sequelize.fn('ISJSON', sequelize.col('userDetails')), 1)
})

// JSON_VALUE - extract a scalar value from a JSON string
User.findAll({
  attributes: [[ sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), 'address line 1']]
})

// JSON_VALUE - query a scalar value from a JSON string
User.findAll({
  where: sequelize.where(sequelize.fn('JSON_VALUE', sequelize.col('userDetails'), '$.address.Line1'), '14, Foo Street')
})

// JSON_QUERY - extract an object or array
User.findAll({
  attributes: [[ sequelize.fn('JSON_QUERY', sequelize.col('userDetails'), '$.address'), 'full address']]
})</code>
</code></pre><h3>JSONB</h3><p>JSONB can be queried in three different ways.</p><h4>Nested object</h4><pre><code class="lang-js"><code class="source-code prettyprint">{
  meta: {
    video: {
      url: {
        [Op.ne]: null
      }
    }
  }
}</code>
</code></pre><h4>Nested key</h4><pre><code class="lang-js"><code class="source-code prettyprint">{
  "meta.audio.length": {
    [Op.gt]: 20
  }
}</code>
</code></pre><h4>Containment</h4><pre><code class="lang-js"><code class="source-code prettyprint">{
  "meta": {
    [Op.contains]: {
      site: {
        url: 'http://google.com'
      }
    }
  }
}</code>
</code></pre><h3>Relations / Associations</h3><pre><code class="lang-js"><code class="source-code prettyprint">// Find all projects with a least one task where task.state === project.state
Project.findAll({
    include: [{
        model: Task,
        where: { state: Sequelize.col('project.state') }
    }]
})</code>
</code></pre><h2>Pagination / Limiting</h2><pre><code class="lang-js"><code class="source-code prettyprint">// Fetch 10 instances/rows
Project.findAll({ limit: 10 })

// Skip 8 instances/rows
Project.findAll({ offset: 8 })

// Skip 5 instances and fetch the 5 after that
Project.findAll({ offset: 5, limit: 5 })</code>
</code></pre><h2>Ordering</h2><p><code>order</code> takes an array of items to order the query by or a sequelize method. Generally you will want to use a tuple/array of either attribute, direction or just direction to ensure proper escaping.</p><pre><code class="lang-js"><code class="source-code prettyprint">Subtask.findAll({
  order: [
    // Will escape title and validate DESC against a list of valid direction parameters
    ['title', 'DESC'],

    // Will order by max(age)
    sequelize.fn('max', sequelize.col('age')),

    // Will order by max(age) DESC
    [sequelize.fn('max', sequelize.col('age')), 'DESC'],

    // Will order by  otherfunction(`col1`, 12, 'lalala') DESC
    [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],

    // Will order an associated model's created_at using the model name as the association's name.
    [Task, 'createdAt', 'DESC'],

    // Will order through an associated model's created_at using the model names as the associations' names.
    [Task, Project, 'createdAt', 'DESC'],

    // Will order by an associated model's created_at using the name of the association.
    ['Task', 'createdAt', 'DESC'],

    // Will order by a nested associated model's created_at using the names of the associations.
    ['Task', 'Project', 'createdAt', 'DESC'],

    // Will order by an associated model's created_at using an association object. (preferred method)
    [Subtask.associations.Task, 'createdAt', 'DESC'],

    // Will order by a nested associated model's created_at using association objects. (preferred method)
    [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],

    // Will order by an associated model's created_at using a simple association object.
    [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],

    // Will order by a nested associated model's created_at simple association objects.
    [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
  ]

  // Will order by max age descending
  order: sequelize.literal('max(age) DESC')

  // Will order by max age ascending assuming ascending is the default order when direction is omitted
  order: sequelize.fn('max', sequelize.col('age'))

  // Will order by age ascending assuming ascending is the default order when direction is omitted
  order: sequelize.col('age')

  // Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
  order: sequelize.random()
})</code>
</code></pre><h2>Table Hint</h2><p><code>tableHint</code> can be used to optionally pass a table hint when using mssql. The hint must be a value from <code>Sequelize.TableHints</code> and should only be used when absolutely necessary. Only a single table hint is currently supported per query.</p><p>Table hints override the default behavior of mssql query optimizer by specifying certain options. They only affect the table or view referenced in that clause.</p><pre><code class="lang-js"><code class="source-code prettyprint">const TableHints = Sequelize.TableHints;

Project.findAll({
  // adding the table hint NOLOCK
  tableHint: TableHints.NOLOCK
  // this will generate the SQL 'WITH (NOLOCK)'
})</code>
</code></pre><h2>Index Hints</h2><p><code>indexHints</code> can be used to optionally pass index hints when using mysql. The hint type must be a value from <code>Sequelize.IndexHints</code> and the values should reference existing indexes.</p><p>Index hints <a href="https://dev.mysql.com/doc/refman/5.7/en/index-hints.html">override the default behavior of the mysql query optimizer</a>.</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.findAll({
  indexHints: [
    { type: IndexHints.USE, values: ['index_project_on_name'] }
  ],
  where: {
    id: {
      [Op.gt]: 623
    },
    name: {
      [Op.like]: 'Foo %'
    }
  }
})</code>
</code></pre><p>Will generate a mysql query that looks like this:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM Project USE INDEX (index_project_on_name) WHERE name LIKE 'FOO %' AND id &gt; 623;</code>
</code></pre><p><code>Sequelize.IndexHints</code> includes <code>USE</code>, <code>FORCE</code>, and <code>IGNORE</code>.</p><p>See <a href="https://github.com/sequelize/sequelize/issues/9421">Issue #9421</a> for the original API proposal.</p></div>
        <a data-ice="link" href="/v5/manual/querying.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Instances</h1><h2>Building a non-persistent instance</h2><p>In order to create instances of defined classes just do as follows. You might recognize the syntax if you coded Ruby in the past. Using the <code>build</code>-method will return an unsaved object, which you explicitly have to save.</p><pre><code class="lang-js"><code class="source-code prettyprint">const project = Project.build({
  title: 'my awesome project',
  description: 'woot woot. this will make me a rich man'
})

const task = Task.build({
  title: 'specify the project idea',
  description: 'bla',
  deadline: new Date()
})</code>
</code></pre><p>Built instances will automatically get default values when they were defined:</p><pre><code class="lang-js"><code class="source-code prettyprint">// first define the model
class Task extends Model {}
Task.init({
  title: Sequelize.STRING,
  rating: { type: Sequelize.TINYINT, defaultValue: 3 }
}, { sequelize, modelName: 'task' });

// now instantiate an object
const task = Task.build({title: 'very important task'})

task.title  // ==&gt; 'very important task'
task.rating // ==&gt; 3</code>
</code></pre><p>To get it stored in the database, use the <code>save</code>-method and catch the events ... if needed:</p><pre><code class="lang-js"><code class="source-code prettyprint">project.save().then(() =&gt; {
  // my nice callback stuff
})

task.save().catch(error =&gt; {
  // mhhh, wth!
})

// you can also build, save and access the object with chaining:
Task
  .build({ title: 'foo', description: 'bar', deadline: new Date() })
  .save()
  .then(anotherTask =&gt; {
    // you can now access the currently saved task with the variable anotherTask... nice!
  })
  .catch(error =&gt; {
    // Ooops, do some error-handling
  })</code>
</code></pre><h2>Creating persistent instances</h2><p>While an instance created with <code>.build()</code> requires an explicit <code>.save()</code> call to be stored in the database, <code>.create()</code> omits that requirement altogether and automatically stores your instance's data once called.</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task =&gt; {
  // you can now access the newly created task via the variable task
})</code>
</code></pre><p>It is also possible to define which attributes can be set via the create method. This can be especially very handy if you create database entries based on a form which can be filled by a user. Using that would for example allow you to restrict the <code>User</code> model to set only a username and an address but not an admin flag:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user =&gt; {
  // let's assume the default of isAdmin is false:
  console.log(user.get({
    plain: true
  })) // =&gt; { username: 'barfooz', isAdmin: false }
})</code>
</code></pre><h2>Updating / Saving / Persisting an instance</h2><p>Now lets change some values and save changes to the database... There are two ways to do that:</p><pre><code class="lang-js"><code class="source-code prettyprint">// way 1
task.title = 'a very different title now'
task.save().then(() =&gt; {})

// way 2
task.update({
  title: 'a very different title now'
}).then(() =&gt; {})</code>
</code></pre><p>It's also possible to define which attributes should be saved when calling <code>save</code>, by passing an array of column names. This is useful when you set attributes based on a previously defined object. E.g. if you get the values of an object via a form of a web app. Furthermore this is used internally for <code>update</code>. This is how it looks like:</p><pre><code class="lang-js"><code class="source-code prettyprint">task.title = 'foooo'
task.description = 'baaaaaar'
task.save({fields: ['title']}).then(() =&gt; {
 // title will now be 'foooo' but description is the very same as before
})

// The equivalent call using update looks like this:
task.update({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(() =&gt; {
 // title will now be 'foooo' but description is the very same as before
})</code>
</code></pre><p>When you call <code>save</code> without changing any attribute, this method will execute nothing;</p><h2>Destroying / Deleting persistent instances</h2><p>Once you created an object and got a reference to it, you can delete it from the database. The relevant method is <code>destroy</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.create({ title: 'a task' }).then(task =&gt; {
  // now you see me...
  return task.destroy();
}).then(() =&gt; {
 // now i'm gone :)
})</code>
</code></pre><p>If the <code>paranoid</code> options is true, the object will not be deleted, instead the <code>deletedAt</code> column will be set to the current timestamp. To force the deletion, you can pass <code>force: true</code> to the destroy call:</p><pre><code class="lang-js"><code class="source-code prettyprint">task.destroy({ force: true })</code>
</code></pre><p>After an object is soft deleted in <code>paranoid</code> mode, you will not be able to create a new instance with the same primary key
until you have force-deleted the old instance.</p><h2>Restoring soft-deleted instances</h2><p>If you have soft-deleted an instance of a model with <code>paranoid: true</code>, and would like to undo the deletion, use the <code>restore</code> method:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.create({ title: 'a task' }).then(task =&gt; {
  // now you see me...
  return task.destroy();
}).then((task) =&gt; {
  // now i'm gone, but wait...
  return task.restore();
})</code>
</code></pre><h2>Working in bulk (creating, updating and destroying multiple rows at once)</h2><p>In addition to updating a single instance, you can also create, update, and delete multiple instances at once. The functions you are looking for are called</p><ul>
<li><code>Model.bulkCreate</code></li>
<li><code>Model.update</code></li>
<li><code>Model.destroy</code></li>
</ul><p>Since you are working with multiple models, the callbacks will not return DAO instances. BulkCreate will return an array of model instances/DAOs, they will however, unlike <code>create</code>, not have the resulting values of autoIncrement attributes.<code>update</code> and <code>destroy</code> will return the number of affected rows.</p><p>First lets look at bulkCreate</p><pre><code class="lang-js"><code class="source-code prettyprint">User.bulkCreate([
  { username: 'barfooz', isAdmin: true },
  { username: 'foo', isAdmin: true },
  { username: 'bar', isAdmin: false }
]).then(() =&gt; { // Notice: There are no arguments here, as of right now you'll have to...
  return User.findAll();
}).then(users =&gt; {
  console.log(users) // ... in order to get the array of user objects
})</code>
</code></pre><p>Insert several rows and return all columns (Postgres only):</p><pre><code class="lang-js"><code class="source-code prettyprint">User.bulkCreate([
  { username: 'barfooz', isAdmin: true },
  { username: 'foo', isAdmin: true },
  { username: 'bar', isAdmin: false }
], { returning: true }) // will return all columns for each row inserted
.then((result) =&gt; {
  console.log(result);
});</code>
</code></pre><p>Insert several rows and return specific columns (Postgres only):</p><pre><code class="lang-js"><code class="source-code prettyprint">User.bulkCreate([
  { username: 'barfooz', isAdmin: true },
  { username: 'foo', isAdmin: true },
  { username: 'bar', isAdmin: false }
], { returning: ['username'] }) // will return only the specified columns for each row inserted
.then((result) =&gt; {
  console.log(result);
});</code>
</code></pre><p>To update several rows at once:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.bulkCreate([
  {subject: 'programming', status: 'executing'},
  {subject: 'reading', status: 'executing'},
  {subject: 'programming', status: 'finished'}
]).then(() =&gt; {
  return Task.update(
    { status: 'inactive' }, /* set attributes' value */
    { where: { subject: 'programming' }} /* where criteria */
  );
}).then(([affectedCount, affectedRows]) =&gt; {
  // Notice that affectedRows will only be defined in dialects which support returning: true

  // affectedCount will be 2
  return Task.findAll();
}).then(tasks =&gt; {
  console.log(tasks) // the 'programming' tasks will both have a status of 'inactive'
})</code>
</code></pre><p>And delete them:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.bulkCreate([
  {subject: 'programming', status: 'executing'},
  {subject: 'reading', status: 'executing'},
  {subject: 'programming', status: 'finished'}
]).then(() =&gt; {
  return Task.destroy({
    where: {
      subject: 'programming'
    },
    truncate: true /* this will ignore where and truncate the table instead */
  });
}).then(affectedRows =&gt; {
  // affectedRows will be 2
  return Task.findAll();
}).then(tasks =&gt; {
  console.log(tasks) // no programming, just reading :(
})</code>
</code></pre><p>If you are accepting values directly from the user, it might be beneficial to limit the columns that you want to actually insert.<code>bulkCreate()</code>accepts an options object as the second parameter. The object can have a <code>fields</code> parameter, (an array) to let it know which fields you want to build explicitly</p><pre><code class="lang-js"><code class="source-code prettyprint">User.bulkCreate([
  { username: 'foo' },
  { username: 'bar', admin: true}
], { fields: ['username'] }).then(() =&gt; {
  // nope bar, you can't be admin!
})</code>
</code></pre><p><code>bulkCreate</code> was originally made to be a mainstream/fast way of inserting records, however, sometimes you want the luxury of being able to insert multiple rows at once without sacrificing model validations even when you explicitly tell Sequelize which columns to sift through. You can do by adding a <code>validate: true</code> property to the options object.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Tasks extends Model {}
Tasks.init({
  name: {
    type: Sequelize.STRING,
    validate: {
      notNull: { args: true, msg: 'name cannot be null' }
    }
  },
  code: {
    type: Sequelize.STRING,
    validate: {
      len: [3, 10]
    }
  }
}, { sequelize, modelName: 'tasks' })

Tasks.bulkCreate([
  {name: 'foo', code: '123'},
  {code: '1234'},
  {name: 'bar', code: '1'}
], { validate: true }).catch(errors =&gt; {
  /* console.log(errors) would look like:
  [
    { record:
    ...
    name: 'SequelizeBulkRecordError',
    message: 'Validation error',
    errors:
      { name: 'SequelizeValidationError',
        message: 'Validation error',
        errors: [Object] } },
    { record:
      ...
      name: 'SequelizeBulkRecordError',
      message: 'Validation error',
      errors:
        { name: 'SequelizeValidationError',
        message: 'Validation error',
        errors: [Object] } }
  ]
  */
})</code>
</code></pre><h2>Values of an instance</h2><p>If you log an instance you will notice, that there is a lot of additional stuff. In order to hide such stuff and reduce it to the very interesting information, you can use the<code>get</code>-attribute. Calling it with the option <code>plain</code> = true will only return the values of an instance.</p><pre><code class="lang-js"><code class="source-code prettyprint">Person.create({
  name: 'Rambow',
  firstname: 'John'
}).then(john =&gt; {
  console.log(john.get({
    plain: true
  }))
})

// result:

// { name: 'Rambow',
//   firstname: 'John',
//   id: 1,
//   createdAt: Tue, 01 May 2012 19:12:16 GMT,
//   updatedAt: Tue, 01 May 2012 19:12:16 GMT
// }</code>
</code></pre><p><strong>Hint:</strong>You can also transform an instance into JSON by using <code>JSON.stringify(instance)</code>. This will basically return the very same as <code>values</code>.</p><h2>Reloading instances</h2><p>If you need to get your instance in sync, you can use the method<code>reload</code>. It will fetch the current data from the database and overwrite the attributes of the model on which the method has been called on.</p><pre><code class="lang-js"><code class="source-code prettyprint">Person.findOne({ where: { name: 'john' } }).then(person =&gt; {
  person.name = 'jane'
  console.log(person.name) // 'jane'

  person.reload().then(() =&gt; {
    console.log(person.name) // 'john'
  })
})</code>
</code></pre><h2>Incrementing</h2><p>In order to increment values of an instance without running into concurrency issues, you may use <code>increment</code>.</p><p>First of all you can define a field and the value you want to add to it.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findByPk(1).then(user =&gt; {
  return user.increment('my-integer-field', {by: 2})
}).then(user =&gt; {
  // Postgres will return the updated user by default (unless disabled by setting { returning: false })
  // In other dialects, you'll want to call user.reload() to get the updated instance...
})</code>
</code></pre><p>Second, you can define multiple fields and the value you want to add to them.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findByPk(1).then(user =&gt; {
  return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)</code>
</code></pre><p>Third, you can define an object containing fields and its increment values.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findByPk(1).then(user =&gt; {
  return user.increment({
    'my-integer-field':    2,
    'my-very-other-field': 3
  })
}).then(/* ... */)</code>
</code></pre><h2>Decrementing</h2><p>In order to decrement values of an instance without running into concurrency issues, you may use <code>decrement</code>.</p><p>First of all you can define a field and the value you want to add to it.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findByPk(1).then(user =&gt; {
  return user.decrement('my-integer-field', {by: 2})
}).then(user =&gt; {
  // Postgres will return the updated user by default (unless disabled by setting { returning: false })
  // In other dialects, you'll want to call user.reload() to get the updated instance...
})</code>
</code></pre><p>Second, you can define multiple fields and the value you want to add to them.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findByPk(1).then(user =&gt; {
  return user.decrement([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)</code>
</code></pre><p>Third, you can define an object containing fields and its decrement values.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.findByPk(1).then(user =&gt; {
  return user.decrement({
    'my-integer-field':    2,
    'my-very-other-field': 3
  })
}).then(/* ... */)</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/instances.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Associations</h1><p>This section describes the various association types in sequelize. There are four type of
associations available in Sequelize</p><ol>
<li>BelongsTo</li>
<li>HasOne</li>
<li>HasMany</li>
<li>BelongsToMany</li>
</ol><h2>Basic Concepts</h2><h3>Source &amp; Target</h3><p>Let's first begin with a basic concept that you will see used in most associations, <strong>source</strong> and <strong>target</strong> model. Suppose you are trying to add an association between two Models. Here we are adding a <code>hasOne</code> association between <code>User</code> and <code>Project</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({
  name: Sequelize.STRING,
  email: Sequelize.STRING
}, {
  sequelize,
  modelName: 'user'
});

class Project extends Model {}
Project.init({
  name: Sequelize.STRING
}, {
  sequelize,
  modelName: 'project'
});

User.hasOne(Project);</code>
</code></pre><p><code>User</code> model (the model that the function is being invoked on) is the <strong>source</strong>. <code>Project</code> model (the model being passed as an argument) is the <strong>target</strong>.</p><h3>Foreign Keys</h3><p>When you create associations between your models in sequelize, foreign key references with constraints will automatically be created. The setup below:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Task extends Model {}
Task.init({ title: Sequelize.STRING }, { sequelize, modelName: 'task' });
class User extends Model {}
User.init({ username: Sequelize.STRING }, { sequelize, modelName: 'user' });

User.hasMany(Task); // Will add userId to Task model
Task.belongsTo(User); // Will also add userId to Task model</code>
</code></pre><p>Will generate the following SQL:</p><pre><code class="lang-sql"><code class="source-code prettyprint">CREATE TABLE IF NOT EXISTS "users" (
  "id" SERIAL,
  "username" VARCHAR(255),
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "tasks" (
  "id" SERIAL,
  "title" VARCHAR(255),
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "userId" INTEGER REFERENCES "users" ("id") ON DELETE
  SET
    NULL ON UPDATE CASCADE,
    PRIMARY KEY ("id")
);</code>
</code></pre><p>The relation between <code>tasks</code> and <code>users</code> model injects the <code>userId</code> foreign key on <code>tasks</code> table, and marks it as a reference to the <code>users</code> table. By default <code>userId</code> will be set to <code>NULL</code> if the referenced user is deleted, and updated if the id of the <code>userId</code> updated. These options can be overridden by passing <code>onUpdate</code> and <code>onDelete</code> options to the association calls. The validation options are <code>RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL</code>.</p><p>For 1:1 and 1:m associations the default option is <code>SET NULL</code> for deletion, and <code>CASCADE</code> for updates. For n:m, the default for both is <code>CASCADE</code>. This means, that if you delete or update a row from one side of an n:m association, all the rows in the join table referencing that row will also be deleted or updated.</p><h4>underscored option</h4><p>Sequelize allow setting <code>underscored</code> option for Model. When <code>true</code> this option will set the
<code>field</code> option on all attributes to the underscored version of its name. This also applies to
foreign keys generated by associations.</p><p>Let's modify last example to use <code>underscored</code> option.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Task extends Model {}
Task.init({
  title: Sequelize.STRING
}, {
  underscored: true,
  sequelize,
  modelName: 'task'
});

class User extends Model {}
User.init({
  username: Sequelize.STRING
}, {
  underscored: true,
  sequelize,
  modelName: 'user'
});

// Will add userId to Task model, but field will be set to `user_id`
// This means column name will be `user_id`
User.hasMany(Task);

// Will also add userId to Task model, but field will be set to `user_id`
// This means column name will be `user_id`
Task.belongsTo(User);</code>
</code></pre><p>Will generate the following SQL:</p><pre><code class="lang-sql"><code class="source-code prettyprint">CREATE TABLE IF NOT EXISTS "users" (
  "id" SERIAL,
  "username" VARCHAR(255),
  "created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
  "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "tasks" (
  "id" SERIAL,
  "title" VARCHAR(255),
  "created_at" TIMESTAMP WITH TIME ZONE NOT NULL,
  "updated_at" TIMESTAMP WITH TIME ZONE NOT NULL,
  "user_id" INTEGER REFERENCES "users" ("id") ON DELETE
  SET
    NULL ON UPDATE CASCADE,
    PRIMARY KEY ("id")
);</code>
</code></pre><p>With the underscored option attributes injected to model are still camel cased but <code>field</code> option is set to their underscored version.</p><h4>Cyclic dependencies &amp; Disabling constraints</h4><p>Adding constraints between tables means that tables must be created in the database in a certain order, when using <code>sequelize.sync</code>. If <code>Task</code> has a reference to <code>User</code>, the <code>users</code> table must be created before the <code>tasks</code> table can be created. This can sometimes lead to circular references, where sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has a reference to its current version.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Document extends Model {}
Document.init({
  author: Sequelize.STRING
}, { sequelize, modelName: 'document' });
class Version extends Model {}
Version.init({
  timestamp: Sequelize.DATE
}, { sequelize, modelName: 'version' });

Document.hasMany(Version); // This adds documentId attribute to version
Document.belongsTo(Version, {
  as: 'Current',
  foreignKey: 'currentVersionId'
}); // This adds currentVersionId attribute to document</code>
</code></pre><p>However, the code above will result in the following error: <code>Cyclic dependency found. documents is dependent of itself. Dependency chain: documents -&gt; versions =&gt; documents</code>.</p><p>In order to alleviate that, we can pass <code>constraints: false</code> to one of the associations:</p><pre><code class="lang-js"><code class="source-code prettyprint">Document.hasMany(Version);
Document.belongsTo(Version, {
  as: 'Current',
  foreignKey: 'currentVersionId',
  constraints: false
});</code>
</code></pre><p>Which will allow us to sync the tables correctly:</p><pre><code class="lang-sql"><code class="source-code prettyprint">CREATE TABLE IF NOT EXISTS "documents" (
  "id" SERIAL,
  "author" VARCHAR(255),
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "currentVersionId" INTEGER,
  PRIMARY KEY ("id")
);

CREATE TABLE IF NOT EXISTS "versions" (
  "id" SERIAL,
  "timestamp" TIMESTAMP WITH TIME ZONE,
  "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
  "documentId" INTEGER REFERENCES "documents" ("id") ON DELETE
  SET
    NULL ON UPDATE CASCADE,
    PRIMARY KEY ("id")
);</code>
</code></pre><h4>Enforcing a foreign key reference without constraints</h4><p>Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Trainer extends Model {}
Trainer.init({
  firstName: Sequelize.STRING,
  lastName: Sequelize.STRING
}, { sequelize, modelName: 'trainer' });

// Series will have a trainerId = Trainer.id foreign reference key
// after we call Trainer.hasMany(series)
class Series extends Model {}
Series.init({
  title: Sequelize.STRING,
  subTitle: Sequelize.STRING,
  description: Sequelize.TEXT,
  // Set FK relationship (hasMany) with `Trainer`
  trainerId: {
    type: Sequelize.INTEGER,
    references: {
      model: Trainer,
      key: 'id'
    }
  }
}, { sequelize, modelName: 'series' });

// Video will have seriesId = Series.id foreign reference key
// after we call Series.hasOne(Video)
class Video extends Model {}
Video.init({
  title: Sequelize.STRING,
  sequence: Sequelize.INTEGER,
  description: Sequelize.TEXT,
  // set relationship (hasOne) with `Series`
  seriesId: {
    type: Sequelize.INTEGER,
    references: {
      model: Series, // Can be both a string representing the table name or a Sequelize model
      key: 'id'
    }
  }
}, { sequelize, modelName: 'video' });

Series.hasOne(Video);
Trainer.hasMany(Series);</code>
</code></pre><h2>One-To-One associations</h2><p>One-To-One associations are associations between exactly two models connected by a single foreign key.</p><h3>BelongsTo</h3><p>BelongsTo associations are associations where the foreign key for the one-to-one relation exists on the <strong>source model</strong>.</p><p>A simple example would be a <strong>Player</strong> being part of a <strong>Team</strong> with the foreign key on the player.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Player extends Model {}
Player.init({/* attributes */}, { sequelize, modelName: 'player' });
class Team extends Model {}
Team.init({/* attributes */}, { sequelize, modelName: 'team' });

Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team</code>
</code></pre><h4>Foreign keys</h4><p>By default the foreign key for a belongsTo relation will be generated from the target model name and the target primary key name.</p><p>The default casing is <code>camelCase</code>. If the source model is configured with <code>underscored: true</code> the foreignKey will be created with field <code>snake_case</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });

// will add companyId to user
User.belongsTo(Company);

class User extends Model {}
User.init({/* attributes */}, { underscored: true, sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({
  uuid: {
    type: Sequelize.UUID,
    primaryKey: true
  }
}, { sequelize, modelName: 'company' });

// will add companyUuid to user with field company_uuid
User.belongsTo(Company);</code>
</code></pre><p>In cases where <code>as</code> has been defined it will be used in place of the target model name.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class UserRole extends Model {}
UserRole.init({/* attributes */}, { sequelize, modelName: 'userRole' });

User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId</code>
</code></pre><p>In all cases the default foreign key can be overwritten with the <code>foreignKey</code> option.
When the foreign key option is used, Sequelize will use it as-is:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });

User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User</code>
</code></pre><h4>Target keys</h4><p>The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the <code>targetKey</code> option.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });

User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User</code>
</code></pre><h3>HasOne</h3><p>HasOne associations are associations where the foreign key for the one-to-one relation exists on the <strong>target model</strong>.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* ... */}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({/* ... */}, { sequelize, modelName: 'project' })

// One-way associations
Project.hasOne(User)

/*
  In this example hasOne will add an attribute projectId to the User model!
  Furthermore, Project.prototype will gain the methods getUser and setUser according
  to the first parameter passed to define. If you have underscore style
  enabled, the added attribute will be project_id instead of projectId.

  The foreign key will be placed on the users table.

  You can also define the foreign key, e.g. if you already have an existing
  database and want to work on it:
*/

Project.hasOne(User, { foreignKey: 'initiator_id' })

/*
  Because Sequelize will use the model's name (first parameter of define) for
  the accessor methods, it is also possible to pass a special option to hasOne:
*/

Project.hasOne(User, { as: 'Initiator' })
// Now you will get Project.getInitiator and Project.setInitiator

// Or let's define some self references
class Person extends Model {}
Person.init({ /* ... */}, { sequelize, modelName: 'person' })

Person.hasOne(Person, {as: 'Father'})
// this will add the attribute FatherId to Person

// also possible:
Person.hasOne(Person, {as: 'Father', foreignKey: 'DadId'})
// this will add the attribute DadId to Person

// In both cases you will be able to do:
Person.setFather
Person.getFather

// If you need to join a table twice you can double join the same table
Team.hasOne(Game, {as: 'HomeTeam', foreignKey : 'homeTeamId'});
Team.hasOne(Game, {as: 'AwayTeam', foreignKey : 'awayTeamId'});

Game.belongsTo(Team);</code>
</code></pre><p>Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.</p><h4>Source keys</h4><p>The source key is the attribute on the source model that the foreign key attribute on the target model points to. By default the source key for a <code>hasOne</code> relation will be the source model's primary attribute. To use a custom attribute, use the <code>sourceKey</code> option.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* attributes */}, { sequelize, modelName: 'user' })
class Company extends Model {}
Company.init({/* attributes */}, { sequelize, modelName: 'company' });

// Adds companyName attribute to User
// Use name attribute from Company as source attribute
Company.hasOne(User, {foreignKey: 'companyName', sourceKey: 'name'});</code>
</code></pre><h3>Difference between HasOne and BelongsTo</h3><p>In Sequelize 1:1 relationship can be set using HasOne and BelongsTo. They are suitable for different scenarios. Lets study this difference using an example.</p><p>Suppose we have two tables to link <strong>Player</strong> and <strong>Team</strong>. Lets define their models.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Player extends Model {}
Player.init({/* attributes */}, { sequelize, modelName: 'player' })
class Team extends Model {}
Team.init({/* attributes */}, { sequelize, modelName: 'team' });</code>
</code></pre><p>When we link two models in Sequelize we can refer them as pairs of <strong>source</strong> and <strong>target</strong> models. Like this</p><p>Having <strong>Player</strong> as the <strong>source</strong> and <strong>Team</strong> as the <strong>target</strong></p><pre><code class="lang-js"><code class="source-code prettyprint">Player.belongsTo(Team);
//Or
Player.hasOne(Team);</code>
</code></pre><p>Having <strong>Team</strong> as the <strong>source</strong> and <strong>Player</strong> as the <strong>target</strong></p><pre><code class="lang-js"><code class="source-code prettyprint">Team.belongsTo(Player);
//Or
Team.hasOne(Player);</code>
</code></pre><p>HasOne and BelongsTo insert the association key in different models from each other. HasOne inserts the association key in <strong>target</strong> model whereas BelongsTo inserts the association key in the <strong>source</strong> model.</p><p>Here is an example demonstrating use cases of BelongsTo and HasOne.</p><pre><code class="lang-js"><code class="source-code prettyprint">class Player extends Model {}
Player.init({/* attributes */}, { sequelize, modelName: 'player' })
class Coach extends Model {}
Coach.init({/* attributes */}, { sequelize, modelName: 'coach' })
class Team extends Model {}
Team.init({/* attributes */}, { sequelize, modelName: 'team' });</code>
</code></pre><p>Suppose our <code>Player</code> model has information about its team as <code>teamId</code> column. Information about each Team's <code>Coach</code> is stored in the <code>Team</code> model as <code>coachId</code> column. These both scenarios requires different kind of 1:1 relation because foreign key relation is present on different models each time.</p><p>When information about association is present in <strong>source</strong> model we can use <code>belongsTo</code>. In this case <code>Player</code> is suitable for <code>belongsTo</code> because it has <code>teamId</code> column.</p><pre><code class="lang-js"><code class="source-code prettyprint">Player.belongsTo(Team)  // `teamId` will be added on Player / Source model</code>
</code></pre><p>When information about association is present in <strong>target</strong> model we can use <code>hasOne</code>. In this case <code>Coach</code> is suitable for <code>hasOne</code> because <code>Team</code> model store information about its <code>Coach</code> as <code>coachId</code> field.</p><pre><code class="lang-js"><code class="source-code prettyprint">Coach.hasOne(Team)  // `coachId` will be added on Team / Target model</code>
</code></pre><h2>One-To-Many associations (hasMany)</h2><p>One-To-Many associations are connecting one source with multiple targets. The targets however are again connected to exactly one specific source.</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({/* ... */}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({/* ... */}, { sequelize, modelName: 'project' })

// OK. Now things get more complicated (not really visible to the user :)).
// First let's define a hasMany association
Project.hasMany(User, {as: 'Workers'})</code>
</code></pre><p>This will add the attribute <code>projectId</code> to User. Depending on your setting for underscored the column in the table will either be called <code>projectId</code> or <code>project_id</code>. Instances of Project will get the accessors <code>getWorkers</code> and <code>setWorkers</code>.</p><p>Sometimes you may need to associate records on different columns, you may use <code>sourceKey</code> option:</p><pre><code class="lang-js"><code class="source-code prettyprint">class City extends Model {}
City.init({ countryCode: Sequelize.STRING }, { sequelize, modelName: 'city' });
class Country extends Model {}
Country.init({ isoCode: Sequelize.STRING }, { sequelize, modelName: 'country' });

// Here we can connect countries and cities base on country code
Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
City.belongsTo(Country, {foreignKey: 'countryCode', targetKey: 'isoCode'});</code>
</code></pre><p>So far we dealt with a one-way association. But we want more! Let's define it the other way around by creating a many to many association in the next section.</p><h2>Belongs-To-Many associations</h2><p>Belongs-To-Many associations are used to connect sources with multiple targets. Furthermore the targets can also have connections to multiple sources.</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.belongsToMany(User, {through: 'UserProject'});
User.belongsToMany(Project, {through: 'UserProject'});</code>
</code></pre><p>This will create a new model called UserProject with the equivalent foreign keys <code>projectId</code> and <code>userId</code>. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).</p><p>Defining <code>through</code> is <strong>required</strong>. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.</p><p>This will add methods <code>getUsers</code>, <code>setUsers</code>, <code>addUser</code>,<code>addUsers</code> to <code>Project</code>, and <code>getProjects</code>, <code>setProjects</code>, <code>addProject</code>, and <code>addProjects</code> to <code>User</code>.</p><p>Sometimes you may want to rename your models when using them in associations. Let's define users as workers and projects as tasks by using the alias (<code>as</code>) option. We will also manually define the foreign keys to use:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId' })
Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId' })</code>
</code></pre><p><code>foreignKey</code> will allow you to set <strong>source model</strong> key in the <strong>through</strong> relation.
<code>otherKey</code> will allow you to set <strong>target model</strong> key in the <strong>through</strong> relation.</p><pre><code class="lang-js"><code class="source-code prettyprint">User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId', otherKey: 'projectId'})</code>
</code></pre><p>Of course you can also define self references with belongsToMany:</p><pre><code class="lang-js"><code class="source-code prettyprint">Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
// This will create the table PersonChildren which stores the ids of the objects.
</code>
</code></pre><h4>Source and target keys</h4><p>If you want to create a belongs to many relationship that does not use the default primary key some setup work is required.
You must set the <code>sourceKey</code> (optionally <code>targetKey</code>) appropriately for the two ends of the belongs to many. Further you must also ensure you have appropriate indexes created on your relationships. For example:</p><pre><code class="lang-js"><code class="source-code prettyprint">const User = this.sequelize.define('User', {
  id: {
    type: DataTypes.UUID,
    allowNull: false,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4,
    field: 'user_id'
  },
  userSecondId: {
    type: DataTypes.UUID,
    allowNull: false,
    defaultValue: DataTypes.UUIDV4,
    field: 'user_second_id'
  }
}, {
  tableName: 'tbl_user',
  indexes: [
    {
      unique: true,
      fields: ['user_second_id']
    }
  ]
});

const Group = this.sequelize.define('Group', {
  id: {
    type: DataTypes.UUID,
    allowNull: false,
    primaryKey: true,
    defaultValue: DataTypes.UUIDV4,
    field: 'group_id'
  },
  groupSecondId: {
    type: DataTypes.UUID,
    allowNull: false,
    defaultValue: DataTypes.UUIDV4,
    field: 'group_second_id'
  }
}, {
  tableName: 'tbl_group',
  indexes: [
    {
      unique: true,
      fields: ['group_second_id']
    }
  ]
});

User.belongsToMany(Group, {
  through: 'usergroups',
  sourceKey: 'userSecondId'
});
Group.belongsToMany(User, {
  through: 'usergroups',
  sourceKey: 'groupSecondId'
});</code>
</code></pre><p>If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:</p><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({}, { sequelize, modelName: 'project' })
class UserProjects extends Model {}
UserProjects.init({
  status: DataTypes.STRING
}, { sequelize, modelName: 'userProjects' })

User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })</code>
</code></pre><p>To add a new project to a user and set its status, you pass extra <code>options.through</code> to the setter, which contains the attributes for the join table</p><pre><code class="lang-js"><code class="source-code prettyprint">user.addProject(project, { through: { status: 'started' }})</code>
</code></pre><p>By default the code above will add projectId and userId to the UserProjects table, and <em>remove any previously defined primary key attribute</em> - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns. To enforce a primary key on the <code>UserProjects</code> model you can add it manually.</p><pre><code class="lang-js"><code class="source-code prettyprint">class UserProjects extends Model {}
UserProjects.init({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  status: DataTypes.STRING
}, { sequelize, modelName: 'userProjects' })</code>
</code></pre><p>With Belongs-To-Many you can query based on <strong>through</strong> relation and select specific attributes. For example using <code>findAll</code> with <strong>through</strong></p><pre><code class="lang-js"><code class="source-code prettyprint">User.findAll({
  include: [{
    model: Project,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {completed: true}
    }
  }]
});</code>
</code></pre><p>Belongs-To-Many creates a unique key when primary key is not present on through model. This unique key name can be overridden using <strong>uniqueKey</strong> option.</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.belongsToMany(User, { through: UserProjects, uniqueKey: 'my_custom_unique' })</code>
</code></pre><h2>Naming strategy</h2><p>By default sequelize will use the model name (the name passed to <code>sequelize.define</code>) to figure out the name of the model when used in associations. For example, a model named <code>user</code> will add the functions <code>get/set/add User</code> to instances of the associated model, and a property named <code>.user</code> in eager loading, while a model named <code>User</code> will add the same functions, but a property named <code>.User</code> (notice the upper case U) in eager loading.</p><p>As we've already seen, you can alias models in associations using <code>as</code>. In single associations (has one and belongs to), the alias should be singular, while for many associations (has many) it should be plural. Sequelize then uses the <a href="https://www.npmjs.org/package/inflection">inflection</a> library to convert the alias to its singular form. However, this might not always work for irregular or non-english words. In this case, you can provide both the plural and the singular form of the alias:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.belongsToMany(Project, { as: { singular: 'task', plural: 'tasks' }})
// Notice that inflection has no problem singularizing tasks, this is just for illustrative purposes.</code>
</code></pre><p>If you know that a model will always use the same alias in associations, you can provide it when creating the model</p><pre><code class="lang-js"><code class="source-code prettyprint">class Project extends Model {}
Project.init(attributes, {
  name: {
    singular: 'task',
    plural: 'tasks',
  },
  sequelize,
  modelName: 'project'
})

User.belongsToMany(Project);</code>
</code></pre><p>This will add the functions <code>add/set/get Tasks</code> to user instances.</p><p>Remember, that using <code>as</code> to change the name of the association will also change the name of the foreign key. When using <code>as</code>, it is safest to also specify the foreign key.</p><pre><code class="lang-js"><code class="source-code prettyprint">Invoice.belongsTo(Subscription)
Subscription.hasMany(Invoice)</code>
</code></pre><p>Without <code>as</code>, this adds <code>subscriptionId</code> as expected. However, if you were to say <code>Invoice.belongsTo(Subscription, { as: 'TheSubscription' })</code>, you will have both <code>subscriptionId</code> and <code>theSubscriptionId</code>, because sequelize is not smart enough to figure that the calls are two sides of the same relation. 'foreignKey' fixes this problem;</p><pre><code class="lang-js"><code class="source-code prettyprint">Invoice.belongsTo(Subscription, { as: 'TheSubscription', foreignKey: 'subscription_id' })
Subscription.hasMany(Invoice, { foreignKey: 'subscription_id' })</code>
</code></pre><h2>Associating objects</h2><p>Because Sequelize is doing a lot of magic, you have to call <code>Sequelize.sync</code> after setting the associations! Doing so will allow you the following:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.hasMany(Task)
Task.belongsTo(Project)

Project.create()...
Task.create()...
Task.create()...

// save them... and then:
project.setTasks([task1, task2]).then(() =&gt; {
  // saved!
})

// ok, now they are saved... how do I get them later on?
project.getTasks().then(associatedTasks =&gt; {
  // associatedTasks is an array of tasks
})

// You can also pass filters to the getter method.
// They are equal to the options you can pass to a usual finder method.
project.getTasks({ where: 'id &gt; 10' }).then(tasks =&gt; {
  // tasks with an id greater than 10 :)
})

// You can also only retrieve certain fields of a associated object.
project.getTasks({attributes: ['title']}).then(tasks =&gt; {
  // retrieve tasks with the attributes "title" and "id"
})</code>
</code></pre><p>To remove created associations you can just call the set method without a specific id:</p><pre><code class="lang-js"><code class="source-code prettyprint">// remove the association with task1
project.setTasks([task2]).then(associatedTasks =&gt; {
  // you will get task2 only
})

// remove 'em all
project.setTasks([]).then(associatedTasks =&gt; {
  // you will get an empty array
})

// or remove 'em more directly
project.removeTask(task1).then(() =&gt; {
  // it's gone
})

// and add 'em again
project.addTask(task1).then(() =&gt; {
  // it's back again
})</code>
</code></pre><p>You can of course also do it vice versa:</p><pre><code class="lang-js"><code class="source-code prettyprint">// project is associated with task1 and task2
task2.setProject(null).then(() =&gt; {
  // and it's gone
})</code>
</code></pre><p>For hasOne/belongsTo it's basically the same:</p><pre><code class="lang-js"><code class="source-code prettyprint">Task.hasOne(User, {as: "Author"})
Task.setAuthor(anAuthor)</code>
</code></pre><p>Adding associations to a relation with a custom join table can be done in two ways (continuing with the associations defined in the previous chapter):</p><pre><code class="lang-js"><code class="source-code prettyprint">// Either by adding a property with the name of the join table model to the object, before creating the association
project.UserProjects = {
  status: 'active'
}
u.addProject(project)

// Or by providing a second options.through argument when adding the association, containing the data that should go in the join table
u.addProject(project, { through: { status: 'active' }})


// When associating multiple objects, you can combine the two options above. In this case the second argument
// will be treated as a defaults object, that will be used if no data is provided
project1.UserProjects = {
    status: 'inactive'
}

u.setProjects([project1, project2], { through: { status: 'active' }})
// The code above will record inactive for project one, and active for project two in the join table</code>
</code></pre><p>When getting data on an association that has a custom join table, the data from the join table will be returned as a DAO instance:</p><pre><code class="lang-js"><code class="source-code prettyprint">u.getProjects().then(projects =&gt; {
  const project = projects[0]

  if (project.UserProjects.status === 'active') {
    // .. do magic

    // since this is a real DAO instance, you can save it directly after you are done doing magic
    return project.UserProjects.save()
  }
})</code>
</code></pre><p>If you only need some of the attributes from the join table, you can provide an array with the attributes you want:</p><pre><code class="lang-js"><code class="source-code prettyprint">// This will select only name from the Projects table, and only status from the UserProjects table
user.getProjects({ attributes: ['name'], joinTableAttributes: ['status']})</code>
</code></pre><h2>Check associations</h2><p>You can also check if an object is already associated with another one (N:M only). Here is how you'd do it:</p><pre><code class="lang-js"><code class="source-code prettyprint">// check if an object is one of associated ones:
Project.create({ /* */ }).then(project =&gt; {
  return User.create({ /* */ }).then(user =&gt; {
    return project.hasUser(user).then(result =&gt; {
      // result would be false
      return project.addUser(user).then(() =&gt; {
        return project.hasUser(user).then(result =&gt; {
          // result would be true
        })
      })
    })
  })
})

// check if all associated objects are as expected:
// let's assume we have already a project and two users
project.setUsers([user1, user2]).then(() =&gt; {
  return project.hasUsers([user1]);
}).then(result =&gt; {
  // result would be true
  return project.hasUsers([user1, user2]);
}).then(result =&gt; {
  // result would be true
})</code>
</code></pre><h2>Advanced Concepts</h2><h3>Scopes</h3><p>This section concerns association scopes. For a definition of association scopes vs. scopes on associated models, see <a href="/v5/./manual/scopes.html">Scopes</a>.</p><p>Association scopes allow you to place a scope (a set of default attributes for <code>get</code> and <code>create</code>) on the association. Scopes can be placed both on the associated model (the target of the association), and on the through table for n:m relations.</p><h4>1:n</h4><p>Assume we have models Comment, Post, and Image. A comment can be associated to either an image or a post via <code>commentableId</code> and <code>commentable</code> - we say that Post and Image are <code>Commentable</code></p><pre><code class="lang-js"><code class="source-code prettyprint">class Post extends Model {}
Post.init({
  title: Sequelize.STRING,
  text: Sequelize.STRING
}, { sequelize, modelName: 'post' });

class Image extends Model {}
Image.init({
  title: Sequelize.STRING,
  link: Sequelize.STRING
}, { sequelize, modelName: 'image' });

class Comment extends Model {
  getItem(options) {
    return this[
      'get' +
        this.get('commentable')
          [0]
          .toUpperCase() +
        this.get('commentable').substr(1)
    ](options);
  }
}

Comment.init({
  title: Sequelize.STRING,
  commentable: Sequelize.STRING,
  commentableId: Sequelize.INTEGER
}, { sequelize, modelName: 'comment' });

Post.hasMany(Comment, {
  foreignKey: 'commentableId',
  constraints: false,
  scope: {
    commentable: 'post'
  }
});

Comment.belongsTo(Post, {
  foreignKey: 'commentableId',
  constraints: false,
  as: 'post'
});

Image.hasMany(Comment, {
  foreignKey: 'commentableId',
  constraints: false,
  scope: {
    commentable: 'image'
  }
});

Comment.belongsTo(Image, {
  foreignKey: 'commentableId',
  constraints: false,
  as: 'image'
});</code>
</code></pre><p><code>constraints: false</code> disables references constraints, as <code>commentableId</code> column references several tables, we cannot add a <code>REFERENCES</code> constraint to it.</p><p>Note that the Image -&gt; Comment and Post -&gt; Comment relations define a scope, <code>commentable: 'image'</code> and <code>commentable: 'post'</code> respectively. This scope is automatically applied when using the association functions:</p><pre><code class="lang-js"><code class="source-code prettyprint">image.getComments()
// SELECT "id", "title", "commentable", "commentableId", "createdAt", "updatedAt" FROM "comments" AS
// "comment" WHERE "comment"."commentable" = 'image' AND "comment"."commentableId" = 1;

image.createComment({
  title: 'Awesome!'
})
// INSERT INTO "comments" ("id","title","commentable","commentableId","createdAt","updatedAt") VALUES
// (DEFAULT,'Awesome!','image',1,'2018-04-17 05:36:40.454 +00:00','2018-04-17 05:36:40.454 +00:00')
// RETURNING *;

image.addComment(comment);
// UPDATE "comments" SET "commentableId"=1,"commentable"='image',"updatedAt"='2018-04-17 05:38:43.948
// +00:00' WHERE "id" IN (1)</code>
</code></pre><p>The <code>getItem</code> utility function on <code>Comment</code> completes the picture - it simply converts the <code>commentable</code> string into a call to either <code>getImage</code> or <code>getPost</code>, providing an abstraction over whether a comment belongs to a post or an image. You can pass a normal options object as a parameter to <code>getItem(options)</code> to specify any where conditions or includes.</p><h4>n:m</h4><p>Continuing with the idea of a polymorphic model, consider a tag table - an item can have multiple tags, and a tag can be related to several items.</p><p>For brevity, the example only shows a Post model, but in reality Tag would be related to several other models.</p><pre><code class="lang-js"><code class="source-code prettyprint">class ItemTag extends Model {}
ItemTag.init({
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  tagId: {
    type: Sequelize.INTEGER,
    unique: 'item_tag_taggable'
  },
  taggable: {
    type: Sequelize.STRING,
    unique: 'item_tag_taggable'
  },
  taggableId: {
    type: Sequelize.INTEGER,
    unique: 'item_tag_taggable',
    references: null
  }
}, { sequelize, modelName: 'item_tag' });

class Tag extends Model {}
Tag.init({
  name: Sequelize.STRING,
  status: Sequelize.STRING
}, { sequelize, modelName: 'tag' });

Post.belongsToMany(Tag, {
  through: {
    model: ItemTag,
    unique: false,
    scope: {
      taggable: 'post'
    }
  },
  foreignKey: 'taggableId',
  constraints: false
});

Tag.belongsToMany(Post, {
  through: {
    model: ItemTag,
    unique: false
  },
  foreignKey: 'tagId',
  constraints: false
});</code>
</code></pre><p>Notice that the scoped column (<code>taggable</code>) is now on the through model (<code>ItemTag</code>).</p><p>We could also define a more restrictive association, for example, to get all pending tags for a post by applying a scope of both the through model (<code>ItemTag</code>) and the target model (<code>Tag</code>):</p><pre><code class="lang-js"><code class="source-code prettyprint">Post.belongsToMany(Tag, {
  through: {
    model: ItemTag,
    unique: false,
    scope: {
      taggable: 'post'
    }
  },
  scope: {
    status: 'pending'
  },
  as: 'pendingTags',
  foreignKey: 'taggableId',
  constraints: false
});

post.getPendingTags();</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT
  "tag"."id",
  "tag"."name",
  "tag"."status",
  "tag"."createdAt",
  "tag"."updatedAt",
  "item_tag"."id" AS "item_tag.id",
  "item_tag"."tagId" AS "item_tag.tagId",
  "item_tag"."taggable" AS "item_tag.taggable",
  "item_tag"."taggableId" AS "item_tag.taggableId",
  "item_tag"."createdAt" AS "item_tag.createdAt",
  "item_tag"."updatedAt" AS "item_tag.updatedAt"
FROM
  "tags" AS "tag"
  INNER JOIN "item_tags" AS "item_tag" ON "tag"."id" = "item_tag"."tagId"
  AND "item_tag"."taggableId" = 1
  AND "item_tag"."taggable" = 'post'
WHERE
  ("tag"."status" = 'pending');</code>
</code></pre><p><code>constraints: false</code> disables references constraints on the <code>taggableId</code> column. Because the column is polymorphic, we cannot say that it <code>REFERENCES</code> a specific table.</p><h3>Creating with associations</h3><p>An instance can be created with nested association in one step, provided all elements are new.</p><h4>BelongsTo / HasMany / HasOne association</h4><p>Consider the following models:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Product extends Model {}
Product.init({
  title: Sequelize.STRING
}, { sequelize, modelName: 'product' });
class User extends Model {}
User.init({
  firstName: Sequelize.STRING,
  lastName: Sequelize.STRING
}, { sequelize, modelName: 'user' });
class Address extends Model {}
Address.init({
  type: Sequelize.STRING,
  line1: Sequelize.STRING,
  line2: Sequelize.STRING,
  city: Sequelize.STRING,
  state: Sequelize.STRING,
  zip: Sequelize.STRING,
}, { sequelize, modelName: 'address' });

Product.User = Product.belongsTo(User);
User.Addresses = User.hasMany(Address);
// Also works for `hasOne`</code>
</code></pre><p>A new <code>Product</code>, <code>User</code>, and one or more <code>Address</code> can be created in one step in the following way:</p><pre><code class="lang-js"><code class="source-code prettyprint">return Product.create({
  title: 'Chair',
  user: {
    firstName: 'Mick',
    lastName: 'Broadstone',
    addresses: [{
      type: 'home',
      line1: '100 Main St.',
      city: 'Austin',
      state: 'TX',
      zip: '78704'
    }]
  }
}, {
  include: [{
    association: Product.User,
    include: [ User.Addresses ]
  }]
});</code>
</code></pre><p>Here, our user model is called <code>user</code>, with a lowercase u - This means that the property in the object should also be <code>user</code>. If the name given to <code>sequelize.define</code> was <code>User</code>, the key in the object should also be <code>User</code>. Likewise for <code>addresses</code>, except it's pluralized being a <code>hasMany</code> association.</p><h4>BelongsTo association with an alias</h4><p>The previous example can be extended to support an association alias.</p><pre><code class="lang-js"><code class="source-code prettyprint">const Creator = Product.belongsTo(User, { as: 'creator' });

return Product.create({
  title: 'Chair',
  creator: {
    firstName: 'Matt',
    lastName: 'Hansen'
  }
}, {
  include: [ Creator ]
});</code>
</code></pre><h4>HasMany / BelongsToMany association</h4><p>Let's introduce the ability to associate a product with many tags. Setting up the models could look like:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Tag extends Model {}
Tag.init({
  name: Sequelize.STRING
}, { sequelize, modelName: 'tag' });

Product.hasMany(Tag);
// Also works for `belongsToMany`.</code>
</code></pre><p>Now we can create a product with multiple tags in the following way:</p><pre><code class="lang-js"><code class="source-code prettyprint">Product.create({
  id: 1,
  title: 'Chair',
  tags: [
    { name: 'Alpha'},
    { name: 'Beta'}
  ]
}, {
  include: [ Tag ]
})</code>
</code></pre><p>And, we can modify this example to support an alias as well:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Categories = Product.hasMany(Tag, { as: 'categories' });

Product.create({
  id: 1,
  title: 'Chair',
  categories: [
    { id: 1, name: 'Alpha' },
    { id: 2, name: 'Beta' }
  ]
}, {
  include: [{
    association: Categories,
    as: 'categories'
  }]
})</code>
</code></pre><hr></div>
        <a data-ice="link" href="/v5/manual/associations.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Raw queries</h1><p>As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use the function <code>sequelize.query</code>.</p><p>By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query("UPDATE users SET y = 42 WHERE x = 12").then(([results, metadata]) =&gt; {
  // Results will be an empty array and metadata will contain the number of affected rows.
})</code>
</code></pre><p>In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
  .then(users =&gt; {
    // We don't need spread here, since only the results will be returned for select queries
  })</code>
</code></pre><p>Several other query types are available. <a href="https://github.com/sequelize/sequelize/blob/master/lib/query-types.js">Peek into the source for details</a></p><p>A second option is the model. If you pass a model the returned data will be instances of that model.</p><pre><code class="lang-js"><code class="source-code prettyprint">// Callee is the model definition. This allows you to easily map a query to a predefined model
sequelize
  .query('SELECT * FROM projects', {
    model: Projects,
    mapToModel: true // pass true here if you have any mapped fields
  })
  .then(projects =&gt; {
    // Each record will now be an instance of Project
  })</code>
</code></pre><p>See more options in the <a href="/v5/./manual/../class/lib/sequelize.js~Sequelize.html#instance-method-query">query API reference</a>. Some examples below:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT 1', {
  // A function (or false) for logging your queries
  // Will get called for every SQL query that gets sent
  // to the server.
  logging: console.log,

  // If plain is true, then sequelize will only return the first
  // record of the result set. In case of false it will return all records.
  plain: false,

  // Set this to true if you don't have a model definition for your query.
  raw: false,

  // The type of query you are executing. The query type affects how results are formatted before they are passed back.
  type: Sequelize.QueryTypes.SELECT
})

// Note the second argument being null!
// Even if we declared a callee here, the raw: true would
// supersede and return a raw object.
sequelize
  .query('SELECT * FROM projects', { raw: true })
  .then(projects =&gt; {
    console.log(projects)
  })</code>
</code></pre><h2>"Dotted" attributes</h2><p>If an attribute name of the table contains dots, the resulting objects will be nested. This is due to the usage of <a href="https://github.com/mickhansen/dottie.js/">dottie.js</a> under the hood. See below:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('select 1 as `foo.bar.baz`').then(rows =&gt; {
  console.log(JSON.stringify(rows))
})</code>
</code></pre><pre><code class="lang-json"><code class="source-code prettyprint">[{
  "foo": {
    "bar": {
      "baz": 1
    }
  }
}]</code>
</code></pre><h2>Replacements</h2><p>Replacements in a query can be done in two different ways, either using named parameters (starting with <code>:</code>), or unnamed, represented by a <code>?</code>. Replacements are passed in the options object.</p><ul>
<li>If an array is passed, <code>?</code> will be replaced in the order that they appear in the array</li>
<li>If an object is passed, <code>:key</code> will be replaced with the keys from that object. If the object contains keys not found in the query or vice versa, an exception will be thrown.</li>
</ul><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT * FROM projects WHERE status = ?',
  { replacements: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects =&gt; {
  console.log(projects)
})

sequelize.query('SELECT * FROM projects WHERE status = :status ',
  { replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects =&gt; {
  console.log(projects)
})</code>
</code></pre><p>Array replacements will automatically be handled, the following query searches for projects where the status matches an array of values.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT * FROM projects WHERE status IN(:status) ',
  { replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT }
).then(projects =&gt; {
  console.log(projects)
})</code>
</code></pre><p>To use the wildcard operator %, append it to your replacement. The following query matches users with names that start with 'ben'.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
  { replacements: { search_name: 'ben%'  }, type: sequelize.QueryTypes.SELECT }
).then(projects =&gt; {
  console.log(projects)
})</code>
</code></pre><h2>Bind Parameter</h2><p>Bind parameters are like replacements. Except replacements are escaped and inserted into the query by sequelize before the query is sent to the database, while bind parameters are sent to the database outside the SQL query text. A query can have either bind parameters or replacements. Bind parameters are referred to by either $1, $2, ... (numeric) or $key (alpha-numeric). This is independent of the dialect.</p><ul>
<li>If an array is passed, <code>$1</code> is bound to the 1st element in the array (<code>bind[0]</code>)</li>
<li>If an object is passed, <code>$key</code> is bound to <code>object['key']</code>. Each key must begin with a non-numeric char. <code>$1</code> is not a valid key, even if <code>object['1']</code> exists.</li>
<li>In either case <code>$$</code> can be used to escape a literal <code>$</code> sign.</li>
</ul><p>The array or object must contain all bound values or Sequelize will throw an exception. This applies even to cases in which the database may ignore the bound parameter.</p><p>The database may add further restrictions to this. Bind parameters cannot be SQL keywords, nor table or column names. They are also ignored in quoted text or data. In PostgreSQL it may also be needed to typecast them, if the type cannot be inferred from the context <code>$1::varchar</code>.</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
  { bind: ['active'], type: sequelize.QueryTypes.SELECT }
).then(projects =&gt; {
  console.log(projects)
})

sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
  { bind: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(projects =&gt; {
  console.log(projects)
})</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/raw-queries.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Transactions</h1><p>Sequelize supports two ways of using transactions:</p><ol>
<li><strong>Managed</strong>, One which will automatically commit or rollback the transaction based on the result of a promise chain and, (if CLS enabled) pass the transaction to all calls within the callback</li>
<li><strong>Unmanaged</strong>, One which leaves committing, rolling back and passing the transaction to the user</li>
</ol><p>The key difference is that the managed transaction uses a callback that expects a promise to be returned to it while the unmanaged transaction returns a promise.</p><h2>Managed transaction (auto-callback)</h2><p>Managed transactions handle committing or rolling back the transaction automatically. You start a managed transaction by passing a callback to <code>sequelize.transaction</code>.</p><p>Notice how the callback passed to <code>transaction</code> returns a promise chain, and does not explicitly call <code>t.commit()</code> nor <code>t.rollback()</code>. If all promises in the returned chain are resolved successfully the transaction is committed. If one or several of the promises are rejected, the transaction is rolled back.</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction(t =&gt; {

  // chain all your queries here. make sure you return them.
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user =&gt; {
    return user.setShooter({
      firstName: 'John',
      lastName: 'Boothe'
    }, {transaction: t});
  });

}).then(result =&gt; {
  // Transaction has been committed
  // result is whatever the result of the promise chain returned to the transaction callback
}).catch(err =&gt; {
  // Transaction has been rolled back
  // err is whatever rejected the promise chain returned to the transaction callback
});</code>
</code></pre><h3>Throw errors to rollback</h3><p>When using the managed transaction you should <em>never</em> commit or rollback the transaction manually. If all queries are successful, but you still want to rollback the transaction (for example because of a validation failure) you should throw an error to break and reject the chain:</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction(t =&gt; {
  return User.create({
    firstName: 'Abraham',
    lastName: 'Lincoln'
  }, {transaction: t}).then(user =&gt; {
    // Woops, the query was successful but we still want to roll back!
    throw new Error();
  });
});</code>
</code></pre><h3>Automatically pass transactions to all queries</h3><p>In the examples above, the transaction is still manually passed, by passing <code>{ transaction: t }</code> as the second argument. To automatically pass the transaction to all queries you must install the <a href="https://github.com/othiym23/node-continuation-local-storage">continuation local storage</a> (CLS) module and instantiate a namespace in your own code:</p><pre><code class="lang-js"><code class="source-code prettyprint">const cls = require('continuation-local-storage');
const namespace = cls.createNamespace('my-very-own-namespace');</code>
</code></pre><p>To enable CLS you must tell sequelize which namespace to use by using a static method of the sequelize constructor:</p><pre><code class="lang-js"><code class="source-code prettyprint">const Sequelize = require('sequelize');
Sequelize.useCLS(namespace);

new Sequelize(....);</code>
</code></pre><p>Notice, that the <code>useCLS()</code> method is on the <em>constructor</em>, not on an instance of sequelize. This means that all instances will share the same namespace, and that CLS is all-or-nothing - you cannot enable it only for some instances.</p><p>CLS works like a thread-local storage for callbacks. What this means in practice is that different callback chains can access local variables by using the CLS namespace. When CLS is enabled sequelize will set the <code>transaction</code> property on the namespace when a new transaction is created. Since variables set within a callback chain are private to that chain several concurrent transactions can exist at the same time:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction((t1) =&gt; {
  namespace.get('transaction') === t1; // true
});

sequelize.transaction((t2) =&gt; {
  namespace.get('transaction') === t2; // true
});</code>
</code></pre><p>In most case you won't need to access <code>namespace.get('transaction')</code> directly, since all queries will automatically look for a transaction on the namespace:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction((t1) =&gt; {
  // With CLS enabled, the user will be created inside the transaction
  return User.create({ name: 'Alice' });
});</code>
</code></pre><p>After you've used <code>Sequelize.useCLS()</code> all promises returned from sequelize will be patched to maintain CLS context. CLS is a complicated subject - more details in the docs for <a href="https://www.npmjs.com/package/cls-bluebird">cls-bluebird</a>, the patch used to make bluebird promises work with CLS.</p><p><strong>Note:</strong> _<a href="https://github.com/othiym23/node-continuation-local-storage/issues/98#issuecomment-323503807">CLS only supports async/await, at the moment, when using cls-hooked package</a>. Although, <a href="https://github.com/Jeff-Lewis/cls-hooked/blob/master/README.md">cls-hooked</a> relies on <em>experimental API</em> <a href="https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md">async_hooks</a>_</p><h2>Concurrent/Partial transactions</h2><p>You can have concurrent transactions within a sequence of queries or have some of them excluded from any transactions. Use the <code>{transaction: }</code> option to control which transaction a query belong to:</p><p><strong>Warning:</strong> <em>SQLite does not support more than one transaction at the same time.</em></p><h3>Without CLS enabled</h3><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction((t1) =&gt; {
  return sequelize.transaction((t2) =&gt; {
    // With CLS enable, queries here will by default use t2
    // Pass in the `transaction` option to define/alter the transaction they belong to.
    return Promise.all([
        User.create({ name: 'Bob' }, { transaction: null }),
        User.create({ name: 'Mallory' }, { transaction: t1 }),
        User.create({ name: 'John' }) // this would default to t2
    ]);
  });
});</code>
</code></pre><h2>Isolation levels</h2><p>The possible isolations levels to use when starting a transaction:</p><pre><code class="lang-js"><code class="source-code prettyprint">Sequelize.Transaction.ISOLATION_LEVELS.READ_UNCOMMITTED // "READ UNCOMMITTED"
Sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED // "READ COMMITTED"
Sequelize.Transaction.ISOLATION_LEVELS.REPEATABLE_READ  // "REPEATABLE READ"
Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE // "SERIALIZABLE"</code>
</code></pre><p>By default, sequelize uses the isolation level of the database. If you want to use a different isolation level, pass in the desired level as the first argument:</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
  }, (t) =&gt; {

  // your transactions

  });</code>
</code></pre><p>The <code>isolationLevel</code> can either be set globally when initializing the Sequelize instance or
locally for every transaction:</p><pre><code class="lang-js"><code class="source-code prettyprint">// globally
new Sequelize('db', 'user', 'pw', {
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});

// locally
sequelize.transaction({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
});</code>
</code></pre><p><strong>Note:</strong> <em>The SET ISOLATION LEVEL queries are not logged in case of MSSQL as the specified isolationLevel is passed directly to tedious</em></p><h2>Unmanaged transaction (then-callback)</h2><p>Unmanaged transactions force you to manually rollback or commit the transaction. If you don't do that, the transaction will hang until it times out. To start an unmanaged transaction, call <code>sequelize.transaction()</code> without a callback (you can still pass an options object) and call <code>then</code> on the returned promise. Notice that <code>commit()</code> and <code>rollback()</code> returns a promise.</p><pre><code class="lang-js"><code class="source-code prettyprint">return sequelize.transaction().then(t =&gt; {
  return User.create({
    firstName: 'Bart',
    lastName: 'Simpson'
  }, {transaction: t}).then(user =&gt; {
    return user.addSibling({
      firstName: 'Lisa',
      lastName: 'Simpson'
    }, {transaction: t});
  }).then(() =&gt; {
    return t.commit();
  }).catch((err) =&gt; {
    return t.rollback();
  });
});</code>
</code></pre><h2>Usage with other sequelize methods</h2><p>The <code>transaction</code> option goes with most other options, which are usually the first argument of a method.
For methods that take values, like <code>.create</code>, <code>.update()</code>, etc. <code>transaction</code> should be passed to the option in the second argument.
If unsure, refer to the API documentation for the method you are using to be sure of the signature.</p><h2>After commit hook</h2><p>A <code>transaction</code> object allows tracking if and when it is committed.</p><p>An <code>afterCommit</code> hook can be added to both managed and unmanaged transaction objects:</p><pre><code class="lang-js"><code class="source-code prettyprint">sequelize.transaction(t =&gt; {
  t.afterCommit((transaction) =&gt; {
    // Your logic
  });
});

sequelize.transaction().then(t =&gt; {
  t.afterCommit((transaction) =&gt; {
    // Your logic
  });

  return t.commit();
})</code>
</code></pre><p>The function passed to <code>afterCommit</code> can optionally return a promise that will resolve before the promise chain
that created the transaction resolves</p><p><code>afterCommit</code> hooks are <em>not</em> raised if a transaction is rolled back</p><p><code>afterCommit</code> hooks do <em>not</em> modify the return value of the transaction, unlike standard hooks</p><p>You can use the <code>afterCommit</code> hook in conjunction with model hooks to know when a instance is saved and available outside
of a transaction</p><pre><code class="lang-js"><code class="source-code prettyprint">model.afterSave((instance, options) =&gt; {
  if (options.transaction) {
    // Save done within a transaction, wait until transaction is committed to
    // notify listeners the instance has been saved
    options.transaction.afterCommit(() =&gt; /* Notify */)
    return;
  }
  // Save done outside a transaction, safe for callers to fetch the updated model
  // Notify
})</code>
</code></pre><h2>Locks</h2><p>Queries within a <code>transaction</code> can be performed with locks</p><pre><code class="lang-js"><code class="source-code prettyprint">return User.findAll({
  limit: 1,
  lock: true,
  transaction: t1
})</code>
</code></pre><p>Queries within a transaction can skip locked rows</p><pre><code class="lang-js"><code class="source-code prettyprint">return User.findAll({
  limit: 1,
  lock: true,
  skipLocked: true,
  transaction: t2
})</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/transactions.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Scopes</h1><p>Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders, <code>where</code>, <code>include</code>, <code>limit</code> etc.</p><h2>Definition</h2><p>Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Project extends Model {}
Project.init({
  // Attributes
}, {
  defaultScope: {
    where: {
      active: true
    }
  },
  scopes: {
    deleted: {
      where: {
        deleted: true
      }
    },
    activeUsers: {
      include: [
        { model: User, where: { active: true }}
      ]
    },
    random () {
      return {
        where: {
          someNumber: Math.random()
        }
      }
    },
    accessLevel (value) {
      return {
        where: {
          accessLevel: {
            [Op.gte]: value
          }
        }
      }
    }
    sequelize,
    modelName: 'project'
  }
});</code>
</code></pre><p>You can also add scopes after a model has been defined by calling <code>addScope</code>. This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.</p><p>The default scope is always applied. This means, that with the model definition above, <code>Project.findAll()</code> will create the following query:</p><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE active = true</code>
</code></pre><p>The default scope can be removed by calling <code>.unscoped()</code>, <code>.scope(null)</code>, or by invoking another scope:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('deleted').findAll(); // Removes the default scope</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE deleted = true</code>
</code></pre><p>It is also possible to include scoped models in a scope definition. This allows you to avoid duplicating <code>include</code>, <code>attributes</code> or <code>where</code> definitions.
Using the above example, and invoking the <code>active</code> scope on the included User model (rather than specifying the condition directly in that include object):</p><pre><code class="lang-js"><code class="source-code prettyprint">activeUsers: {
  include: [
    { model: User.scope('active')}
  ]
}</code>
</code></pre><h2>Usage</h2><p>Scopes are applied by calling <code>.scope</code> on the model definition, passing the name of one or more scopes. <code>.scope</code> returns a fully functional model instance with all the regular methods: <code>.findAll</code>, <code>.update</code>, <code>.count</code>, <code>.destroy</code> etc. You can save this model instance and reuse it later:</p><pre><code class="lang-js"><code class="source-code prettyprint">const DeletedProjects = Project.scope('deleted');

DeletedProjects.findAll();
// some time passes

// let's look for deleted projects again!
DeletedProjects.findAll();</code>
</code></pre><p>Scopes apply to <code>.find</code>, <code>.findAll</code>, <code>.count</code>, <code>.update</code>, <code>.increment</code> and <code>.destroy</code>.</p><p>Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('random', { method: ['accessLevel', 19]}).findAll();</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE someNumber = 42 AND accessLevel &gt;= 19</code>
</code></pre><h2>Merging</h2><p>Several scopes can be applied simultaneously by passing an array of scopes to <code>.scope</code>, or by passing the scopes as consecutive arguments.</p><pre><code class="lang-js"><code class="source-code prettyprint">// These two are equivalent
Project.scope('deleted', 'activeUsers').findAll();
Project.scope(['deleted', 'activeUsers']).findAll();</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects
INNER JOIN users ON projects.userId = users.id
WHERE projects.deleted = true
AND users.active = true</code>
</code></pre><p>If you want to apply another scope alongside the default scope, pass the key <code>defaultScope</code> to <code>.scope</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('defaultScope', 'deleted').findAll();</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">SELECT * FROM projects WHERE active = true AND deleted = true</code>
</code></pre><p>When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similarly to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign">Object.assign</a>), except for <code>where</code> and <code>include</code>, which will be merged. Consider two scopes:</p><pre><code class="lang-js"><code class="source-code prettyprint">{
  scope1: {
    where: {
      firstName: 'bob',
      age: {
        [Op.gt]: 20
      }
    },
    limit: 2
  },
  scope2: {
    where: {
      age: {
        [Op.gt]: 30
      }
    },
    limit: 10
  }
}</code>
</code></pre><p>Calling <code>.scope('scope1', 'scope2')</code> will yield the following query</p><pre><code class="lang-sql"><code class="source-code prettyprint">WHERE firstName = 'bob' AND age &gt; 30 LIMIT 10</code>
</code></pre><p>Note how <code>limit</code> and <code>age</code> are overwritten by <code>scope2</code>, while <code>firstName</code> is preserved. The <code>limit</code>, <code>offset</code>, <code>order</code>, <code>paranoid</code>, <code>lock</code> and <code>raw</code> fields are overwritten, while <code>where</code> is shallowly merged (meaning that identical keys will be overwritten). The merge strategy for <code>include</code> will be discussed later on.</p><p>Note that <code>attributes</code> keys of multiple applied scopes are merged in such a way that <code>attributes.exclude</code> are always preserved. This allows merging several scopes and never leaking sensitive fields in final scope.</p><p>The same merge logic applies when passing a find object directly to <code>findAll</code> (and similar finders) on a scoped model:</p><pre><code class="lang-js"><code class="source-code prettyprint">Project.scope('deleted').findAll({
  where: {
    firstName: 'john'
  }
})</code>
</code></pre><pre><code class="lang-sql"><code class="source-code prettyprint">WHERE deleted = true AND firstName = 'john'</code>
</code></pre><p>Here the <code>deleted</code> scope is merged with the finder. If we were to pass <code>where: { firstName: 'john', deleted: false }</code> to the finder, the <code>deleted</code> scope would be overwritten.</p><h3>Merging includes</h3><p>Includes are merged recursively based on the models being included. This is a very powerful merge, added on v5, and is better understood with an example.</p><p>Consider four models: Foo, Bar, Baz and Qux, with has-many associations as follows:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Foo extends Model {}
class Bar extends Model {}
class Baz extends Model {}
class Qux extends Model {}
Foo.init({ name: Sequelize.STRING }, { sequelize });
Bar.init({ name: Sequelize.STRING }, { sequelize });
Baz.init({ name: Sequelize.STRING }, { sequelize });
Qux.init({ name: Sequelize.STRING }, { sequelize });
Foo.hasMany(Bar, { foreignKey: 'fooId' });
Bar.hasMany(Baz, { foreignKey: 'barId' });
Baz.hasMany(Qux, { foreignKey: 'bazId' });</code>
</code></pre><p>Now, consider the following four scopes defined on Foo:</p><pre><code class="lang-js"><code class="source-code prettyprint">{
  includeEverything: {
    include: {
      model: this.Bar,
      include: [{
        model: this.Baz,
        include: this.Qux
      }]
    }
  },
  limitedBars: {
    include: [{
      model: this.Bar,
      limit: 2
    }]
  },
  limitedBazs: {
    include: [{
      model: this.Bar,
      include: [{
        model: this.Baz,
        limit: 2
      }]
    }]
  },
  excludeBazName: {
    include: [{
      model: this.Bar,
      include: [{
        model: this.Baz,
        attributes: {
          exclude: ['name']
        }
      }]
    }]
  }
}</code>
</code></pre><p>These four scopes can be deeply merged easily, for example by calling <code>Foo.scope('includeEverything', 'limitedBars', 'limitedBazs', 'excludeBazName').findAll()</code>, which would be entirely equivalent to calling the following:</p><pre><code class="lang-js"><code class="source-code prettyprint">Foo.findAll({
  include: {
    model: this.Bar,
    limit: 2,
    include: [{
      model: this.Baz,
      limit: 2,
      attributes: {
        exclude: ['name']
      },
      include: this.Qux
    }]
  }
});</code>
</code></pre><p>Observe how the four scopes were merged into one. The includes of scopes are merged based on the model being included. If one scope includes model A and another includes model B, the merged result will include both models A and B. On the other hand, if both scopes include the same model A, but with different options (such as nested includes or other attributes), those will be merged recursively, as shown above.</p><p>The merge illustrated above works in the exact same way regardless of the order applied to the scopes. The order would only make a difference if a certain option was set by two different scopes - which is not the case of the above example, since each scope does a different thing.</p><p>This merge strategy also works in the exact same way with options passed to <code>.findAll</code>, <code>.findOne</code> and the like.</p><h2>Associations</h2><p>Sequelize has two different but related scope concepts in relation to associations. The difference is subtle but important:</p><ul>
<li><strong>Association scopes</strong> Allow you to specify default attributes when getting and setting associations - useful when implementing polymorphic associations. This scope is only invoked on the association between the two models, when using the <code>get</code>, <code>set</code>, <code>add</code> and <code>create</code> associated model functions</li>
<li><strong>Scopes on associated models</strong> Allows you to apply default and other scopes when fetching associations, and allows you to pass a scoped model when creating associations. These scopes both apply to regular finds on the model and to find through the association.</li>
</ul><p>As an example, consider the models Post and Comment. Comment is associated to several other models (Image, Video etc.) and the association between Comment and other models is polymorphic, which means that Comment stores a <code>commentable</code> column, in addition to the foreign key <code>commentable_id</code>.</p><p>The polymorphic association can be implemented with an <em>association scope</em> :</p><pre><code class="lang-js"><code class="source-code prettyprint">this.Post.hasMany(this.Comment, {
  foreignKey: 'commentable_id',
  scope: {
    commentable: 'post'
  }
});</code>
</code></pre><p>When calling <code>post.getComments()</code>, this will automatically add <code>WHERE commentable = 'post'</code>. Similarly, when adding new comments to a post, <code>commentable</code> will automagically be set to <code>'post'</code>. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see <a href="/v5/./manual/associations.html#scopes">Association scopes</a></p><p>Consider then, that Post has a default scope which only shows active posts: <code>where: { active: true }</code>. This scope lives on the associated model (Post), and not on the association like the <code>commentable</code> scope did. Just like the default scope is applied when calling <code>Post.findAll()</code>, it is also applied when calling <code>User.getPosts()</code> - this will only return the active posts for that user.</p><p>To disable the default scope, pass <code>scope: null</code> to the getter: <code>User.getPosts({ scope: null })</code>. Similarly, if you want to apply other scopes, pass an array like you would to <code>.scope</code>:</p><pre><code class="lang-js"><code class="source-code prettyprint">User.getPosts({ scope: ['scope1', 'scope2']});</code>
</code></pre><p>If you want to create a shortcut method to a scope on an associated model, you can pass the scoped model to the association. Consider a shortcut to get all deleted posts for a user:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Post extends Model {}
Post.init(attributes, {
  defaultScope: {
    where: {
      active: true
    }
  },
  scopes: {
    deleted: {
      where: {
        deleted: true
      }
    }
  },
  sequelize,
});

User.hasMany(Post); // regular getPosts association
User.hasMany(Post.scope('deleted'), { as: 'deletedPosts' });
</code>
</code></pre><pre><code class="lang-js"><code class="source-code prettyprint">User.getPosts(); // WHERE active = true
User.getDeletedPosts(); // WHERE deleted = true</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/scopes.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Read replication</h1><p>Sequelize supports read replication, i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the write master, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is <strong>not</strong> handled by Sequelize, but should be set up by database backend).</p><pre><code class="lang-js"><code class="source-code prettyprint">const sequelize = new Sequelize('database', null, null, {
  dialect: 'mysql',
  port: 3306
  replication: {
    read: [
      { host: '8.8.8.8', username: 'read-username', password: 'some-password' },
      { host: '9.9.9.9', username: 'another-username', password: null }
    ],
    write: { host: '1.1.1.1', username: 'write-username', password: 'any-password' }
  },
  pool: { // If you want to override the options used for the read/write pool you can do so here
    max: 20,
    idle: 30000
  },
})</code>
</code></pre><p>If you have any general settings that apply to all replicas you do not need to provide them for each instance. In the code above, database name and port is propagated to all replicas. The same will happen for user and password, if you leave them out for any of the replicas. Each replica has the following options:<code>host</code>,<code>port</code>,<code>username</code>,<code>password</code>,<code>database</code>.</p><p>Sequelize uses a pool to manage connections to your replicas. Internally Sequelize will maintain two pools created using <code>pool</code> configuration.</p><p>If you want to modify these, you can pass pool as an options when instantiating Sequelize, as shown above.</p><p>Each <code>write</code> or <code>useMaster: true</code> query will use write pool. For <code>SELECT</code> read pool will be used. Read replica are switched using a basic round robin scheduling.</p></div>
        <a data-ice="link" href="/v5/manual/read-replication.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Migrations</h1><p>Just like you use Git / SVN to manage changes in your source code, you can use migrations to keep track of changes to the database. With migrations you can transfer your existing database into another state and vice versa: Those state transitions are saved in migration files, which describe how to get to the new state and how to revert the changes in order to get back to the old state.</p><p>You will need <a href="https://github.com/sequelize/cli">Sequelize CLI</a>. The CLI ships support for migrations and project bootstrapping.</p><h2>The CLI</h2><h3>Installing CLI</h3><p>Let's start with installing CLI, you can find instructions <a href="https://github.com/sequelize/cli">here</a>. Most preferred way is installing locally like this</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npm install --save sequelize-cli</code>
</code></pre><h3>Bootstrapping</h3><p>To create an empty project you will need to execute <code>init</code> command</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli init</code>
</code></pre><p>This will create following folders</p><ul>
<li><code>config</code>, contains config file, which tells CLI how to connect with database</li>
<li><code>models</code>, contains all models for your project</li>
<li><code>migrations</code>, contains all migration files</li>
<li><code>seeders</code>, contains all seed files</li>
</ul><h4>Configuration</h4><p>Before continuing further we will need to tell CLI how to connect to database. To do that let's open default config file <code>config/config.json</code>. It looks something like this</p><pre><code class="lang-json"><code class="source-code prettyprint">{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": null,
    "database": "database_test",
    "host": "127.0.0.1",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": null,
    "database": "database_production",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }
}</code>
</code></pre><p>Now edit this file and set correct database credentials and dialect. The keys of the objects(ex. "development") are used on <code>model/index.js</code> for matching <code>process.env.NODE_ENV</code> (When undefined, "development" is a default value.).</p><p><strong>Note:</strong> <em>If your database doesn't exists yet, you can just call <code>db:create</code> command. With proper access it will create that database for you.</em></p><h3>Creating first Model (and Migration)</h3><p>Once you have properly configured CLI config file you are ready to create your first migration. It's as simple as executing a simple command.</p><p>We will use <code>model:generate</code> command. This command requires two options</p><ul>
<li><code>name</code>, Name of the model</li>
<li><code>attributes</code>, List of model attributes</li>
</ul><p>Let's create a model named <code>User</code>.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string</code>
</code></pre><p>This will do following</p><ul>
<li>Create a model file <code>user</code> in <code>models</code> folder</li>
<li>Create a migration file with name like <code>XXXXXXXXXXXXXX-create-user.js</code> in <code>migrations</code> folder</li>
</ul><p><strong>Note:</strong> <em>Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.</em></p><h3>Running Migrations</h3><p>Until this step, we haven't inserted anything into the database. We have just created required model and migration files for our first model <code>User</code>. Now to actually create that table in database you need to run <code>db:migrate</code> command.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:migrate</code>
</code></pre><p>This command will execute these steps:</p><ul>
<li>Will ensure a table called <code>SequelizeMeta</code> in database. This table is used to record which migrations have run on the current database</li>
<li>Start looking for any migration files which haven't run yet. This is possible by checking <code>SequelizeMeta</code> table. In this case it will run <code>XXXXXXXXXXXXXX-create-user.js</code> migration, which we created in last step.</li>
<li>Creates a table called <code>Users</code> with all columns as specified in its migration file.</li>
</ul><h3>Undoing Migrations</h3><p>Now our table has been created and saved in database. With migration you can revert to old state by just running a command.</p><p>You can use <code>db:migrate:undo</code>, this command will revert most recent migration.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:migrate:undo</code>
</code></pre><p>You can revert back to initial state by undoing all migrations with <code>db:migrate:undo:all</code> command. You can also revert back to a specific migration by passing its name in <code>--to</code> option.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:migrate:undo:all --to XXXXXXXXXXXXXX-create-posts.js</code>
</code></pre><h3>Creating First Seed</h3><p>Suppose we want to insert some data into a few tables by default. If we follow up on previous example we can consider creating a demo user for <code>User</code> table.</p><p>To manage all data migrations you can use seeders. Seed files are some change in data that can be used to populate database table with sample data or test data.</p><p>Let's create a seed file which will add a demo user to our <code>User</code> table.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli seed:generate --name demo-user</code>
</code></pre><p>This command will create a seed file in <code>seeders</code> folder. File name will look something like <code>XXXXXXXXXXXXXX-demo-user.js</code>. It follows the same <code>up / down</code> semantics as the migration files.</p><p>Now we should edit this file to insert demo user to <code>User</code> table.</p><pre><code class="lang-js"><code class="source-code prettyprint">'use strict';

module.exports = {
  up: (queryInterface, Sequelize) =&gt; {
    return queryInterface.bulkInsert('Users', [{
        firstName: 'John',
        lastName: 'Doe',
        email: 'demo@demo.com',
        createdAt: new Date(),
        updatedAt: new Date()
      }], {});
  },

  down: (queryInterface, Sequelize) =&gt; {
    return queryInterface.bulkDelete('Users', null, {});
  }
};
</code>
</code></pre><h3>Running Seeds</h3><p>In last step you have create a seed file. It's still not committed to database. To do that we need to run a simple command.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:seed:all</code>
</code></pre><p>This will execute that seed file and you will have a demo user inserted into <code>User</code> table.</p><p><strong>Note:</strong> <em>Seeders execution is not stored anywhere unlike migrations, which use the <code>SequelizeMeta</code> table. If you wish to override this please read <code>Storage</code> section</em></p><h3>Undoing Seeds</h3><p>Seeders can be undone if they are using any storage. There are two commands available for that:</p><p>If you wish to undo most recent seed</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:seed:undo</code>
</code></pre><p>If you wish to undo a specific seed</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:seed:undo --seed name-of-seed-as-in-data</code>
</code></pre><p>If you wish to undo all seeds</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:seed:undo:all</code>
</code></pre><h2>Advance Topics</h2><h3>Migration Skeleton</h3><p>The following skeleton shows a typical migration file.</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
  up: (queryInterface, Sequelize) =&gt; {
    // logic for transforming into the new state
  },

  down: (queryInterface, Sequelize) =&gt; {
    // logic for reverting the changes
  }
}</code>
</code></pre><p>We can generate this file using <code>migration:generate</code>. This will create <code>xxx-migration-skeleton.js</code> in your migration folder.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli migration:generate --name migration-skeleton</code>
</code></pre><p>The passed <code>queryInterface</code> object can be used to modify the database. The <code>Sequelize</code> object stores the available data types such as <code>STRING</code> or <code>INTEGER</code>. Function <code>up</code> or <code>down</code> should return a <code>Promise</code>. Let's look at an example:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
  up: (queryInterface, Sequelize) =&gt; {
    return queryInterface.createTable('Person', {
        name: Sequelize.STRING,
        isBetaMember: {
          type: Sequelize.BOOLEAN,
          defaultValue: false,
          allowNull: false
        }
      });
  },
  down: (queryInterface, Sequelize) =&gt; {
    return queryInterface.dropTable('Person');
  }
}</code>
</code></pre><p>The following is an example of a migration that performs two changes in the database, using a transaction to ensure that all instructions are successfully executed or rolled back in case of failure:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
    up: (queryInterface, Sequelize) =&gt; {
        return queryInterface.sequelize.transaction((t) =&gt; {
            return Promise.all([
                queryInterface.addColumn('Person', 'petName', {
                    type: Sequelize.STRING
                }, { transaction: t }),
                queryInterface.addColumn('Person', 'favoriteColor', {
                    type: Sequelize.STRING,
                }, { transaction: t })
            ])
        })
    },

    down: (queryInterface, Sequelize) =&gt; {
        return queryInterface.sequelize.transaction((t) =&gt; {
            return Promise.all([
                queryInterface.removeColumn('Person', 'petName', { transaction: t }),
                queryInterface.removeColumn('Person', 'favoriteColor', { transaction: t })
            ])
        })
    }
};</code>
</code></pre><p>The next is an example of a migration that has a foreign key. You can use references to specify a foreign key:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
  up: (queryInterface, Sequelize) =&gt; {
    return queryInterface.createTable('Person', {
      name: Sequelize.STRING,
      isBetaMember: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
        allowNull: false
      },
      userId: {
        type: Sequelize.INTEGER,
        references: {
          model: {
            tableName: 'users',
            schema: 'schema'
          }
          key: 'id'
        },
        allowNull: false
      },
    });
  },

  down: (queryInterface, Sequelize) =&gt; {
    return queryInterface.dropTable('Person');
  }
}
</code>
</code></pre><p>The next is an example of a migration that has uses async/await where you create an unique index on a new column:</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
  async up(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.addColumn(
        'Person',
        'petName',
        {
          type: Sequelize.STRING,
        },
        { transaction }
      );
      await queryInterface.addIndex(
        'Person',
        'petName',
        {
          fields: 'petName',
          unique: true,
        },
        { transaction }
      );
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },

  async down(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.removeColumn('Person', 'petName', { transaction });
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },
};</code>
</code></pre><h3>The <code>.sequelizerc</code> File</h3><p>This is a special configuration file. It lets you specify following options that you would usually pass as arguments to CLI:</p><ul>
<li><code>env</code>: The environment to run the command in</li>
<li><code>config</code>: The path to the config file</li>
<li><code>options-path</code>: The path to a JSON file with additional options</li>
<li><code>migrations-path</code>: The path to the migrations folder</li>
<li><code>seeders-path</code>: The path to the seeders folder</li>
<li><code>models-path</code>: The path to the models folder</li>
<li><code>url</code>: The database connection string to use. Alternative to using --config files</li>
<li><code>debug</code>: When available show various debug information</li>
</ul><p>Some scenarios where you can use it.</p><ul>
<li>You want to override default path to <code>migrations</code>, <code>models</code>, <code>seeders</code> or <code>config</code> folder.</li>
<li>You want to rename <code>config.json</code> to something else like <code>database.json</code></li>
</ul><p>And a whole lot more. Let's see how you can use this file for custom configuration.</p><p>For starters, let's create an empty file in the root directory of your project.</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ touch .sequelizerc</code>
</code></pre><p>Now let's work with an example config.</p><pre><code class="lang-js"><code class="source-code prettyprint">const path = require('path');

module.exports = {
  'config': path.resolve('config', 'database.json'),
  'models-path': path.resolve('db', 'models'),
  'seeders-path': path.resolve('db', 'seeders'),
  'migrations-path': path.resolve('db', 'migrations')
}</code>
</code></pre><p>With this config you are telling CLI to</p><ul>
<li>Use <code>config/database.json</code> file for config settings</li>
<li>Use <code>db/models</code> as models folder</li>
<li>Use <code>db/seeders</code> as seeders folder</li>
<li>Use <code>db/migrations</code> as migrations folder</li>
</ul><h3>Dynamic Configuration</h3><p>Configuration file is by default a JSON file called <code>config.json</code>. But sometimes you want to execute some code or access environment variables which is not possible in JSON files.</p><p>Sequelize CLI can read from both <code>JSON</code> and <code>JS</code> files. This can be setup with <code>.sequelizerc</code> file. Let see how</p><p>First you need to create a <code>.sequelizerc</code> file in the root folder of your project. This file should override config path to a <code>JS</code> file. Like this</p><pre><code class="lang-js"><code class="source-code prettyprint">const path = require('path');

module.exports = {
  'config': path.resolve('config', 'config.js')
}</code>
</code></pre><p>Now Sequelize CLI will load <code>config/config.js</code> for getting configuration options. Since this is a JS file you can have any code executed and export final dynamic configuration file.</p><p>An example of <code>config/config.js</code> file</p><pre><code class="lang-js"><code class="source-code prettyprint">const fs = require('fs');

module.exports = {
  development: {
    username: 'database_dev',
    password: 'database_dev',
    database: 'database_dev',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  test: {
    username: 'database_test',
    password: null,
    database: 'database_test',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  production: {
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOSTNAME,
    dialect: 'mysql',
    dialectOptions: {
      ssl: {
        ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
      }
    }
  }
};</code>
</code></pre><h3>Using Babel</h3><p>Now you know how to use <code>.sequelizerc</code> file. Now let's see how to use this file to use babel with <code>sequelize-cli</code> setup. This will allow you to write migrations and seeders with ES6/ES7 syntax.</p><p>First install <code>babel-register</code></p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npm i --save-dev babel-register</code>
</code></pre><p>Now let's create <code>.sequelizerc</code> file, it can include any configuration you may want to change for <code>sequelize-cli</code> but in addition to that we want it to register babel for our codebase. Something like this</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ touch .sequelizerc # Create rc file</code>
</code></pre><p>Now include <code>babel-register</code> setup in this file</p><pre><code class="lang-js"><code class="source-code prettyprint">require("babel-register");

const path = require('path');

module.exports = {
  'config': path.resolve('config', 'config.json'),
  'models-path': path.resolve('models'),
  'seeders-path': path.resolve('seeders'),
  'migrations-path': path.resolve('migrations')
}</code>
</code></pre><p>Now CLI will be able to run ES6/ES7 code from migrations/seeders etc. Please keep in mind this depends upon your configuration of <code>.babelrc</code>. Please read more about that at <a href="https://babeljs.io">babeljs.io</a>.</p><h3>Using Environment Variables</h3><p>With CLI you can directly access the environment variables inside the <code>config/config.js</code>. You can use <code>.sequelizerc</code> to tell CLI to use <code>config/config.js</code> for configuration. This is explained in last section.</p><p>Then you can just expose file with proper environment variables.</p><pre><code class="lang-js"><code class="source-code prettyprint">module.exports = {
  development: {
    username: 'database_dev',
    password: 'database_dev',
    database: 'database_dev',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  test: {
    username: process.env.CI_DB_USERNAME,
    password: process.env.CI_DB_PASSWORD,
    database: process.env.CI_DB_NAME,
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  production: {
    username: process.env.PROD_DB_USERNAME,
    password: process.env.PROD_DB_PASSWORD,
    database: process.env.PROD_DB_NAME,
    host: process.env.PROD_DB_HOSTNAME,
    dialect: 'mysql'
  }
};</code>
</code></pre><h3>Specifying Dialect Options</h3><p>Sometime you want to specify a dialectOption, if it's a general config you can just add it in <code>config/config.json</code>. Sometime you want to execute some code to get dialectOptions, you should use dynamic config file for those cases.</p><pre><code class="lang-json"><code class="source-code prettyprint">{
    "production": {
        "dialect":"mysql",
        "dialectOptions": {
            "bigNumberStrings": true
        }
    }
}</code>
</code></pre><h3>Production Usages</h3><p>Some tips around using CLI and migration setup in production environment.</p><p>1) Use environment variables for config settings. This is better achieved with dynamic configuration. A sample production safe configuration may look like.</p><pre><code class="lang-js"><code class="source-code prettyprint">const fs = require('fs');

module.exports = {
  development: {
    username: 'database_dev',
    password: 'database_dev',
    database: 'database_dev',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  test: {
    username: 'database_test',
    password: null,
    database: 'database_test',
    host: '127.0.0.1',
    dialect: 'mysql'
  },
  production: {
    username: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    host: process.env.DB_HOSTNAME,
    dialect: 'mysql',
    dialectOptions: {
      ssl: {
        ca: fs.readFileSync(__dirname + '/mysql-ca-master.crt')
      }
    }
  }
};</code>
</code></pre><p>Our goal is to use environment variables for various database secrets and not accidentally check them in to source control.</p><h3>Storage</h3><p>There are three types of storage that you can use: <code>sequelize</code>, <code>json</code>, and <code>none</code>.</p><ul>
<li><code>sequelize</code> : stores migrations and seeds in a table on the sequelize database</li>
<li><code>json</code> : stores migrations and seeds on a json file</li>
<li><code>none</code> : does not store any migration/seed</li>
</ul><h4>Migration Storage</h4><p>By default the CLI will create a table in your database called <code>SequelizeMeta</code> containing an entry
for each executed migration. To change this behavior, there are three options you can add to the
configuration file. Using <code>migrationStorage</code>, you can choose the type of storage to be used for
migrations. If you choose <code>json</code>, you can specify the path of the file using <code>migrationStoragePath</code>
or the CLI will write to the file <code>sequelize-meta.json</code>. If you want to keep the information in the
database, using <code>sequelize</code>, but want to use a different table, you can change the table name using
<code>migrationStorageTableName</code>. Also you can define a different schema for the <code>SequelizeMeta</code> table by
providing the <code>migrationStorageTableSchema</code> property.</p><pre><code class="lang-json"><code class="source-code prettyprint">{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql",

    // Use a different storage type. Default: sequelize
    "migrationStorage": "json",

    // Use a different file name. Default: sequelize-meta.json
    "migrationStoragePath": "sequelizeMeta.json",

    // Use a different table name. Default: SequelizeMeta
    "migrationStorageTableName": "sequelize_meta",

    // Use a different schema for the SequelizeMeta table
    "migrationStorageTableSchema": "custom_schema"
  }
}</code>
</code></pre><p><strong>Note:</strong> <em>The <code>none</code> storage is not recommended as a migration storage. If you decide to use it, be
aware of the implications of having no record of what migrations did or didn't run.</em></p><h4>Seed Storage</h4><p>By default the CLI will not save any seed that is executed. If you choose to change this behavior (!),
you can use <code>seederStorage</code> in the configuration file to change the storage type. If you choose <code>json</code>,
you can specify the path of the file using <code>seederStoragePath</code> or the CLI will write to the file
<code>sequelize-data.json</code>. If you want to keep the information in the database, using <code>sequelize</code>, you can
specify the table name using <code>seederStorageTableName</code>, or it will default to <code>SequelizeData</code>.</p><pre><code class="lang-json"><code class="source-code prettyprint">{
  "development": {
    "username": "root",
    "password": null,
    "database": "database_development",
    "host": "127.0.0.1",
    "dialect": "mysql",
    // Use a different storage. Default: none
    "seederStorage": "json",
    // Use a different file name. Default: sequelize-data.json
    "seederStoragePath": "sequelizeData.json",
    // Use a different table name. Default: SequelizeData
    "seederStorageTableName": "sequelize_data"
  }
}</code>
</code></pre><h3>Configuration Connection String</h3><p>As an alternative to the <code>--config</code> option with configuration files defining your database, you can
use the <code>--url</code> option to pass in a connection string. For example:</p><pre><code class="lang-bash"><code class="source-code prettyprint">$ npx sequelize-cli db:migrate --url 'mysql://root:password@mysql_host.com/database_name'</code>
</code></pre><h3>Passing Dialect Specific Options</h3><pre><code class="lang-json"><code class="source-code prettyprint">{
    "production": {
        "dialect":"postgres",
        "dialectOptions": {
            // dialect options like SSL etc here
        }
    }
}</code>
</code></pre><h3>Programmatic use</h3><p>Sequelize has a <a href="https://github.com/sequelize/umzug">sister library</a> for programmatically handling execution and logging of migration tasks.</p><h2>Query Interface</h2><p>Using <code>queryInterface</code> object described before you can change database schema. To see full list of public methods it supports check <a href="/v5/./manual/../class/lib/query-interface.js~QueryInterface.html">QueryInterface API</a></p></div>
        <a data-ice="link" href="/v5/manual/migrations.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Resources</h1><h2>Addons &amp; Plugins</h2><h3>ACL</h3><ul>
<li><a href="https://github.com/pumpupapp/ssacl">ssacl</a></li>
<li><a href="https://github.com/mickhansen/ssacl-attribute-roles">ssacl-attribute-roles</a></li>
</ul><h3>Auto Code Generation &amp; Scaffolding</h3><ul>
<li><a href="https://www.datensen.com/">meteor modeler</a> - Desktop tool for visual definition of Sequelize models and asssociations.</li>
<li><a href="https://github.com/tomjschuster/sequelize-ui">sequelize-ui</a> - Online tool for building models, relations and more.</li>
<li><a href="https://github.com/andyforever/sequelizer">sequelizer</a> - A GUI Desktop App for generating Sequelize models. Support for Mysql, Mariadb, Postgres, Sqlite, Mssql.</li>
<li><a href="https://github.com/sequelize/sequelize-auto">sequelize-auto</a> Generating models for SequelizeJS via the command line is another choice.</li>
<li><a href="http://www.pg-generator.com/builtin-templates/sequelize/">pg-generator</a> - Auto generate/scaffold Sequelize models for PostgreSQL database.</li>
<li><a href="https://www.npmjs.com/package/sequelizejs-decorators">sequelizejs-decorators</a> decorators for composing sequelize models</li>
</ul><h3>Autoloader</h3><ul>
<li><a href="https://github.com/boxsnake-nodejs/sequelize-autoload">sequelize-autoload</a> - An autoloader for Sequelize, inspired by <a href="https://www.php-fig.org/psr/psr-0/">PSR-0</a> and <a href="https://www.php-fig.org/psr/psr-4/">PSR-4</a>.</li>
</ul><h3>Caching</h3><ul>
<li><a href="https://github.com/DanielHreben/sequelize-transparent-cache">sequelize-transparent-cache</a></li>
</ul><h3>Filters</h3><ul>
<li><a href="https://www.npmjs.com/package/sequelize-transforms">sequelize-transforms</a> - Add configurable attribute transforms.</li>
</ul><h3>Fixtures / mock data</h3><ul>
<li><a href="https://github.com/olalonde/fixer">Fixer</a></li>
<li><a href="https://github.com/domasx2/sequelize-fixtures">Sequelize-fixtures</a></li>
<li><a href="https://github.com/xudejian/sequelize-fixture">Sequelize-fixture</a></li>
</ul><h3>Hierarchies</h3><ul>
<li><a href="https://www.npmjs.com/package/sequelize-hierarchy">sequelize-hierarchy</a> - Nested hierarchies for Sequelize.</li>
</ul><h3>Historical records / Time travel</h3><ul>
<li><a href="https://github.com/bonaval/sequelize-temporal">sequelize-temporal</a> - Temporal tables (aka historical records)</li>
</ul><h3>Migrations</h3><ul>
<li><a href="https://github.com/sequelize/umzug">umzug</a></li>
</ul><h3>Slugification</h3><ul>
<li><a href="https://www.npmjs.com/package/sequelize-slugify">sequelize-slugify</a> - Add slugs to sequelize models</li>
</ul><h3>Tokens</h3><ul>
<li><a href="https://github.com/pipll/sequelize-tokenify">sequelize-tokenify</a> - Add unique tokens to sequelize models</li>
</ul><h3>Miscellaneous</h3><ul>
<li><a href="https://www.npmjs.com/package/sequelize-deep-update">sequelize-deep-update</a> - Update a sequelize instance and its included associated instances with new properties.</li>
<li><a href="https://www.npmjs.com/package/sequelize-noupdate-attributes">sequelize-noupdate-attributes</a> - Adds no update/readonly attributes support to models.</li>
<li><a href="https://www.npmjs.com/package/sequelize-joi">sequelize-joi</a> - Allows specifying <a href="https://github.com/hapijs/joi">Joi</a> validation schema for JSONB model attributes in Sequelize.</li>
</ul></div>
        <a data-ice="link" href="/v5/manual/resources.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>TypeScript</h1><p>Since v5, Sequelize provides its own TypeScript definitions. Please note that only TS &gt;= 3.1 is supported.</p><p>As Sequelize heavily relies on runtime property assignments, TypeScript won't be very useful out of the box. A decent amount of manual type declarations are needed to make models workable.</p><h2>Installation</h2><p>In order to avoid installation bloat for non TS users, you must install the following typing packages manually:</p><ul>
<li><code>@types/node</code> (this is universally required)</li>
<li><code>@types/validator</code></li>
<li><code>@types/bluebird</code></li>
</ul><h2>Usage</h2><p>Example of a minimal TypeScript project:</p><pre><code class="lang-ts"><code class="source-code prettyprint">import { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';
import { HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';

class User extends Model {
  public id!: number; // Note that the `null assertion` `!` is required in strict mode.
  public name!: string;
  public preferredName!: string | null; // for nullable fields

  // timestamps!
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // Since TS cannot determine model association at compile time
  // we have to declare them here purely virtually
  // these will not exist until `Model.init` was called.

  public getProjects!: HasManyGetAssociationsMixin&lt;Project&gt;; // Note the null assertions!
  public addProject!: HasManyAddAssociationMixin&lt;Project, number&gt;;
  public hasProject!: HasManyHasAssociationMixin&lt;Project, number&gt;;
  public countProjects!: HasManyCountAssociationsMixin;
  public createProject!: HasManyCreateAssociationMixin&lt;Project&gt;;

  // You can also pre-declare possible inclusions, these will only be populated if you
  // actively include a relation.
  public readonly projects?: Project[]; // Note this is optional since it's only populated when explicitly requested in code

  public static associations: {
    projects: Association&lt;User, Project&gt;;
  };
}

const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

class Project extends Model {
  public id!: number;
  public ownerId!: number;
  public name!: string;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

class Address extends Model {
  public userId!: number;
  public address!: string;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

Project.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED, // you can omit the `new` but this is discouraged
    autoIncrement: true,
    primaryKey: true,
  },
  ownerId: {
    type: DataTypes.INTEGER.UNSIGNED,
    allowNull: false,
  },
  name: {
    type: new DataTypes.STRING(128),
    allowNull: false,
  }
}, {
  sequelize,
  tableName: 'projects',
});

User.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: new DataTypes.STRING(128),
    allowNull: false,
  },
  preferredName: {
    type: new DataTypes.STRING(128),
    allowNull: true
  }
}, {
  tableName: 'users',
  sequelize: sequelize, // this bit is important
});

Address.init({
  userId: {
    type: DataTypes.INTEGER.UNSIGNED,
  },
  address: {
    type: new DataTypes.STRING(128),
    allowNull: false,
  }
}, {
  tableName: 'address',
  sequelize: sequelize, // this bit is important
});

// Here we associate which actually populates out pre-declared `association` static and other methods.
User.hasMany(Project, {
  sourceKey: 'id',
  foreignKey: 'ownerId',
  as: 'projects' // this determines the name in `associations`!
});

Address.belongsTo(User, {targetKey: 'id'});
User.hasOne(Address,{sourceKey: 'id'});

async function stuff() {
  // Please note that when using async/await you lose the `bluebird` promise context
  // and you fall back to native
  const newUser = await User.create({
    name: 'Johnny',
    preferredName: 'John',
  });
  console.log(newUser.id, newUser.name, newUser.preferredName);

  const project = await newUser.createProject({
    name: 'first!',
  });

  const ourUser = await User.findByPk(1, {
    include: [User.associations.projects],
    rejectOnEmpty: true, // Specifying true here removes `null` from the return type!
  });
  console.log(ourUser.projects![0].name); // Note the `!` null assertion since TS can't know if we included
                                          // the model or not
}</code>
</code></pre><h2>Usage of <code>sequelize.define</code></h2><p>TypeScript doesn't know how to generate a <code>class</code> definition when we use the <code>sequelize.define</code> method to define a Model. Therefore, we need to do some manual work and declare an interface and a type, and eventually cast the result of <code>.define</code> to the <em>static</em> type.</p><pre><code class="lang-ts"><code class="source-code prettyprint">// We need to declare an interface for our model that is basically what our class would be
interface MyModel extends Model {
  readonly id: number;
}

// Need to declare the static model so `findOne` etc. use correct types.
type MyModelStatic = typeof Model &amp; {
  new (values?: object, options?: BuildOptions): MyModel;
}

// TS can't derive a proper class definition from a `.define` call, therefor we need to cast here.
const MyDefineModel = &lt;MyModelStatic&gt;sequelize.define('MyDefineModel', {
  id: {
    primaryKey: true,
    type: DataTypes.INTEGER.UNSIGNED,
  }
});

function stuffTwo() {
  MyDefineModel.findByPk(1, {
    rejectOnEmpty: true,
  })
  .then(myModel =&gt; {
    console.log(myModel.id);
  });
}
</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/typescript.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Upgrade to v5</h1><p>Sequelize v5 is the next major release after v4</p><h2>Breaking Changes</h2><h3>Support for Node 6 and up</h3><p>Sequelize v5 will only support Node 6 and up <a href="https://github.com/sequelize/sequelize/issues/9015">#9015</a></p><h3>Secure Operators</h3><p>With v4 you started to get a deprecation warning <code>String based operators are now deprecated</code>. Also concept of operators was introduced. These operators are Symbols which prevent hash injection attacks.</p><p><a href="/v5/./manual/querying.html#operators-security">operators-security</a></p><p><strong>With v5</strong></p><ul>
<li>Operators are now enabled by default.</li>
<li>You can still use string operators by passing an operators map in <code>operatorsAliases</code>, but that will give you deprecation warning.</li>
<li>Op.$raw is removed</li>
</ul><h3>Typescript Support</h3><p>Sequelize now ship official typings <a href="https://github.com/sequelize/sequelize/pull/10287">#10287</a>. You can consider migrating away from external typings which may get out of sync.</p><h3>Pooling</h3><p>With v5 Sequelize now use <code>sequelize-pool</code> which is a modernized fork of <code>generic-pool@2.5</code>. You no longer need to call <code>sequelize.close</code> to shutdown pool, this helps with lambda executions. <a href="https://github.com/sequelize/sequelize/issues/8468">#8468</a></p><h3>Model</h3><p><strong>Validators</strong></p><p>Custom validators defined per attribute (as opposed to the custom validators defined in the model's options) now run when the attribute's value is <code>null</code> and <code>allowNull</code> is <code>true</code> (while previously they didn't run and the validation succeeded immediately). To avoid problems when upgrading, please check all your custom validators defined per attribute, where <code>allowNull</code> is <code>true</code>, and make sure all these validators behave correctly when the value is <code>null</code>. See <a href="https://github.com/sequelize/sequelize/issues/9143">#9143</a>.</p><p><strong>Attributes</strong></p><p><code>Model.attributes</code> now removed, use <code>Model.rawAttributes</code>. <a href="https://github.com/sequelize/sequelize/issues/5320">#5320</a></p><p><strong>Note</strong>: <em>Please don't confuse this with <code>options.attributes</code>, they are still valid</em></p><p><strong>Paranoid Mode</strong></p><p>With v5 if <code>deletedAt</code> is set, record will be considered as deleted. <code>paranoid</code> option will only use <code>deletedAt</code> as flag. <a href="https://github.com/sequelize/sequelize/issues/8496">#8496</a></p><p><strong>Model.bulkCreate</strong></p><p><code>updateOnDuplicate</code> option which used to accept boolean and array, now only accepts non-empty array of attributes. <a href="https://github.com/sequelize/sequelize/issues/9288">#9288</a></p><p><strong>Underscored Mode</strong></p><p>Implementation of <code>Model.options.underscored</code> is changed. You can find full specifications <a href="https://github.com/sequelize/sequelize/issues/6423#issuecomment-379472035">here</a>.</p><p>Main outline</p><ol>
<li>Both <code>underscoredAll</code> and <code>underscored</code> options are merged into single <code>underscored</code> option</li>
<li>All attributes are now generated with camelcase naming by default. With the <code>underscored</code> option set to <code>true</code>, the <code>field</code> option for attributes will be set as underscored version of attribute name.</li>
<li><code>underscored</code> will control all attributes including timestamps, version and foreign keys. It will not affect any attribute which already specifies the <code>field</code> option.</li>
</ol><p><a href="https://github.com/sequelize/sequelize/pull/9304">#9304</a></p><p><strong>Removed aliases</strong></p><p>Many model based aliases has been removed <a href="https://github.com/sequelize/sequelize/issues/9372">#9372</a></p><table>
<thead>
<tr>
<th style="text-align:left">Removed in v5</th>
<th style="text-align:left">Official Alternative</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">insertOrUpdate</td>
<td style="text-align:left">upsert</td>
</tr>
<tr>
<td style="text-align:left">find</td>
<td style="text-align:left">findOne</td>
</tr>
<tr>
<td style="text-align:left">findAndCount</td>
<td style="text-align:left">findAndCountAll</td>
</tr>
<tr>
<td style="text-align:left">findOrInitialize</td>
<td style="text-align:left">findOrBuild</td>
</tr>
<tr>
<td style="text-align:left">updateAttributes</td>
<td style="text-align:left">update</td>
</tr>
<tr>
<td style="text-align:left">findById, findByPrimary</td>
<td style="text-align:left">findByPk</td>
</tr>
<tr>
<td style="text-align:left">all</td>
<td style="text-align:left">findAll</td>
</tr>
<tr>
<td style="text-align:left">hook</td>
<td style="text-align:left">addHook</td>
</tr>
</tbody>
</table><h3>Datatypes</h3><p><strong>Range</strong></p><p>Now supports only one standard format <code>[{ value: 1, inclusive: true }, { value: 20, inclusive: false }]</code> <a href="https://github.com/sequelize/sequelize/pull/9364">#9364</a></p><p><strong>Case insensitive text</strong></p><p>Added support for <code>CITEXT</code> for Postgres and SQLite</p><p><strong>Removed</strong></p><p><code>NONE</code> type has been removed, use <code>VIRTUAL</code> instead</p><h3>Hooks</h3><p><strong>Removed aliases</strong></p><p>Hooks aliases has been removed <a href="https://github.com/sequelize/sequelize/issues/9372">#9372</a></p><table>
<thead>
<tr>
<th style="text-align:left">Removed in v5</th>
<th style="text-align:left">Official Alternative</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">[after,before]BulkDelete</td>
<td style="text-align:left">[after,before]BulkDestroy</td>
</tr>
<tr>
<td style="text-align:left">[after,before]Delete</td>
<td style="text-align:left">[after,before]Destroy</td>
</tr>
<tr>
<td style="text-align:left">beforeConnection</td>
<td style="text-align:left">beforeConnect</td>
</tr>
</tbody>
</table><h3>Sequelize</h3><p><strong>Removed aliases</strong></p><p>Prototype references for many constants, objects and classes has been removed <a href="https://github.com/sequelize/sequelize/issues/9372">#9372</a></p><table>
<thead>
<tr>
<th style="text-align:left">Removed in v5</th>
<th style="text-align:left">Official Alternative</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Sequelize.prototype.Utils</td>
<td style="text-align:left">Sequelize.Utils</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.Promise</td>
<td style="text-align:left">Sequelize.Promise</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.TableHints</td>
<td style="text-align:left">Sequelize.TableHints</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.Op</td>
<td style="text-align:left">Sequelize.Op</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.Transaction</td>
<td style="text-align:left">Sequelize.Transaction</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.Model</td>
<td style="text-align:left">Sequelize.Model</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.Deferrable</td>
<td style="text-align:left">Sequelize.Deferrable</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype.Error</td>
<td style="text-align:left">Sequelize.Error</td>
</tr>
<tr>
<td style="text-align:left">Sequelize.prototype[error]</td>
<td style="text-align:left">Sequelize[error]</td>
</tr>
</tbody>
</table><pre><code class="lang-js"><code class="source-code prettyprint">import Sequelize from 'sequelize';
const sequelize = new Sequelize('postgres://user:password@127.0.0.1:mydb');

/**
 * In v4 you can do this
 */
console.log(sequelize.Op === Sequelize.Op) // logs `true`
console.log(sequelize.UniqueConstraintError === Sequelize.UniqueConstraintError) // logs `true`

Model.findAll({
  where: {
    [sequelize.Op.and]: [ // Using sequelize.Op or Sequelize.Op interchangeably
      {
        name: "Abc"
      },
      {
        age: {
          [Sequelize.Op.gte]: 18
        }
      }
    ]
  }
}).catch(sequelize.ConnectionError, () =&gt; {
  console.error('Something wrong with connection?');
});

/**
 * In v5 aliases has been removed from Sequelize prototype
 * You should use Sequelize directly to access Op, Errors etc
 */

Model.findAll({
  where: {
    [Sequelize.Op.and]: [ // Don't use sequelize.Op, use Sequelize.Op instead
      {
        name: "Abc"
      },
      {
        age: {
          [Sequelize.Op.gte]: 18
        }
      }
    ]
  }
}).catch(Sequelize.ConnectionError, () =&gt; {
  console.error('Something wrong with connection?');
});</code>
</code></pre><h3>Query Interface</h3><ul>
<li><code>changeColumn</code> no longer generates constraint with <code>_idx</code> suffix. Now Sequelize does not specify any name for constraints thus defaulting to database engine naming. This aligns behavior of <code>sync</code>, <code>createTable</code> and <code>changeColumn</code>.</li>
<li><code>addIndex</code> aliases options aliases have been removed, use the following instead.<ul>
<li><code>indexName</code> =&gt; <code>name</code></li>
<li><code>indicesType</code> =&gt; <code>type</code></li>
<li><code>indexType</code>/<code>method</code> =&gt; <code>using</code></li>
</ul>
</li>
</ul><h3>Others</h3><ul>
<li>Sequelize now use parameterized queries for all INSERT / UPDATE operations (except UPSERT). They provide better protection against SQL Injection attack.</li>
<li><code>ValidationErrorItem</code> now holds reference to original error in the <code>original</code> property, rather than the <code>__raw</code> property.</li>
<li><a href="https://github.com/mickhansen/retry-as-promised">retry-as-promised</a> has been updated to <code>3.1.0</code>, which use <a href="https://github.com/kevinbeaty/any-promise">any-promise</a>. This module repeat all <code>sequelize.query</code> operations. You can configure <code>any-promise</code> to use <code>bluebird</code> for better performance on Node 4 or 6</li>
<li>Sequelize will throw for all <code>undefined</code> keys in <code>where</code> options, In past versions <code>undefined</code> was converted to <code>null</code>.</li>
</ul><h3>Dialect Specific</h3><h4>MSSQL</h4><ul>
<li>Sequelize now works with <code>tedious &gt;= 6.0.0</code>. Old <code>dialectOptions</code> has to be updated to match their new format. Please refer to tedious <a href="http://tediousjs.github.io/tedious/api-connection.html#function_newConnection">documentation</a>. An example of new <code>dialectOptions</code> is given below</li>
</ul><pre><code class="lang-javascript"><code class="source-code prettyprint">dialectOptions: {
  authentication: {
    domain: 'my-domain'
  },
  options: {
    requestTimeout: 60000,
    cryptoCredentialsDetails: {
      ciphers: "RC4-MD5"
    }
  }
}</code>
</code></pre><h4>MySQL</h4><ul>
<li>Requires <code>mysql2 &gt;= 1.5.2</code> for prepared statements</li>
</ul><h4>MariaDB</h4><ul>
<li><code>dialect: 'mariadb'</code> is now <a href="https://github.com/sequelize/sequelize/pull/10192">supported</a> with <code>mariadb</code> package</li>
</ul><h3>Packages</h3><ul>
<li>removed: terraformer-wkt-parser <a href="https://github.com/sequelize/sequelize/pull/9545">#9545</a></li>
<li>removed: <code>generic-pool</code></li>
<li>added: <code>sequelize-pool</code></li>
</ul><h2>Changelog</h2><h3>5.0.0-beta.17</h3><ul>
<li>fix(build): default null for multiple primary keys</li>
<li>fix(util): improve performance of classToInvokable <a href="https://github.com/sequelize/sequelize/pull/10534">#10534</a></li>
<li>fix(model/update): propagate paranoid to individualHooks query <a href="https://github.com/sequelize/sequelize/pull/10369">#10369</a></li>
<li>fix(association): use minimal select for hasAssociation <a href="https://github.com/sequelize/sequelize/pull/10529">#10529</a></li>
<li>fix(query-interface): reject with error for describeTable <a href="https://github.com/sequelize/sequelize/pull/10528">#10528</a></li>
<li>fix(model): throw for invalid include type <a href="https://github.com/sequelize/sequelize/pull/10527">#10527</a></li>
<li>fix(types): additional options for db.query and add missing retry <a href="https://github.com/sequelize/sequelize/pull/10512">#10512</a></li>
<li>fix(query): don't prepare options &amp; sql for every retry <a href="https://github.com/sequelize/sequelize/pull/10498">#10498</a></li>
<li>feat: expose Sequelize.BaseError</li>
<li>feat: upgrade to <code>tedious@6.0.0</code> <a href="https://github.com/sequelize/sequelize/pull/10494">#10494</a></li>
<li>feat(sqlite/query-generator): support restart identity for truncate-table <a href="https://github.com/sequelize/sequelize/pull/10522">#10522</a></li>
<li>feat(data-types): handle numbers passed as objects <a href="https://github.com/sequelize/sequelize/pull/10492">#10492</a></li>
<li>feat(types): enabled string association <a href="https://github.com/sequelize/sequelize/pull/10481">#10481</a></li>
<li>feat(postgres): allow customizing client_min_messages <a href="https://github.com/sequelize/sequelize/pull/10448">#10448</a></li>
<li>refactor(data-types): move to classes <a href="https://github.com/sequelize/sequelize/pull/10495">#10495</a></li>
<li>docs(legacy): fix N:M example <a href="https://github.com/sequelize/sequelize/pull/10509">#10509</a></li>
<li>docs(migrations): use migrationStorageTableSchema <a href="https://github.com/sequelize/sequelize/pull/10417">#10417</a></li>
<li>docs(hooks): add documentation for connection hooks <a href="https://github.com/sequelize/sequelize/pull/10410">#10410</a></li>
<li>docs(addIndex): concurrently option <a href="https://github.com/sequelize/sequelize/pull/10409">#10409</a></li>
<li>docs(model): fix typo <a href="https://github.com/sequelize/sequelize/pull/10405">#10405</a></li>
<li>docs(usage): fix broken link on Basic Usage <a href="https://github.com/sequelize/sequelize/pull/10381">#10381</a></li>
<li>docs(package.json): add homepage <a href="https://github.com/sequelize/sequelize/pull/10372">#10372</a></li>
</ul><h3>5.0.0-beta.16</h3><ul>
<li>feat: add typescript typings <a href="https://github.com/sequelize/sequelize/pull/10117">#10287</a></li>
<li>fix(mysql): match with newlines in error message <a href="https://github.com/sequelize/sequelize/pull/10320">#10320</a></li>
<li>fix(update): skips update when nothing to update <a href="https://github.com/sequelize/sequelize/pull/10248">#10248</a></li>
<li>fix(utils): flattenObject for null values <a href="https://github.com/sequelize/sequelize/pull/10293">#10293</a></li>
<li>fix(instance-validator): don't skip custom validators on null <a href="https://github.com/sequelize/sequelize/pull/9143">#9143</a></li>
<li>docs(transaction): after save example <a href="https://github.com/sequelize/sequelize/pull/10280">#10280</a></li>
<li>docs(query-generator): typo <a href="https://github.com/sequelize/sequelize/pull/10277">#10277</a></li>
<li>refactor(errors): restructure <a href="https://github.com/sequelize/sequelize/pull/10355">#10355</a></li>
<li>refactor(scope): documentation #9087 <a href="https://github.com/sequelize/sequelize/pull/10312">#10312</a></li>
<li>refactor: cleanup association and spread use <a href="https://github.com/sequelize/sequelize/pull/10276">#10276</a></li>
</ul><h3>5.0.0-beta.15</h3><ul>
<li>fix(query-generator): fix addColumn create comment <a href="https://github.com/sequelize/sequelize/pull/10117">#10117</a></li>
<li>fix(sync): throw when no models defined <a href="https://github.com/sequelize/sequelize/pull/10175">#10175</a></li>
<li>fix(association): enable eager load with include all(#9928) <a href="https://github.com/sequelize/sequelize/pull/10173">#10173</a></li>
<li>fix(sqlite): simplify connection error handling</li>
<li>fix(model): prevent version number from being incremented as string <a href="https://github.com/sequelize/sequelize/pull/10217">#10217</a></li>
<li>feat(dialect): mariadb <a href="https://github.com/sequelize/sequelize/pull/10192">#10192</a></li>
<li>docs(migrations): improve dialect options docs</li>
<li>docs: fix favicon <a href="https://github.com/sequelize/sequelize/pull/10242">#10242</a></li>
<li>docs(model.init): <code>attribute.column.validate</code> option <a href="https://github.com/sequelize/sequelize/pull/10237">#10237</a></li>
<li>docs(bulk-create): update support information about ignoreDuplicates</li>
<li>docs: explain custom/new data types <a href="https://github.com/sequelize/sequelize/pull/10170">#10170</a></li>
<li>docs(migrations): Simplify CLI Call <a href="https://github.com/sequelize/sequelize/pull/10201">#10201</a></li>
<li>docs(migrations): added advanced skeleton example <a href="https://github.com/sequelize/sequelize/pull/10190">#10190</a></li>
<li>docs(transaction): default isolation level <a href="https://github.com/sequelize/sequelize/pull/10111">#10111</a></li>
<li>docs: typo in associations.md <a href="https://github.com/sequelize/sequelize/pull/10157">#10157</a></li>
<li>refactor: reduce code complexity <a href="https://github.com/sequelize/sequelize/pull/10120">#10120</a></li>
<li>refactor: optimize memoize use, misc cases <a href="https://github.com/sequelize/sequelize/pull/10122">#10122</a></li>
<li>chore(lint): enforce consistent spacing <a href="https://github.com/sequelize/sequelize/pull/10193">#10193</a></li>
</ul><h3>5.0.0-beta.14</h3><ul>
<li>fix(query): correctly quote identifier for attributes (#9964) <a href="https://github.com/sequelize/sequelize/pull/10118">#10118</a></li>
<li>feat(postgres): dyanmic oids <a href="https://github.com/sequelize/sequelize/pull/10077">#10077</a></li>
<li>fix(error): optimistic lock message <a href="https://github.com/sequelize/sequelize/pull/10068">#10068</a></li>
<li>fix(package): update depd to version 2.0.0 <a href="https://github.com/sequelize/sequelize/pull/10081">#10081</a></li>
<li>fix(model): validate virtual attribute (#9947) <a href="https://github.com/sequelize/sequelize/pull/10085">#10085</a></li>
<li>fix(test): actually test get method with raw option <a href="https://github.com/sequelize/sequelize/pull/10059">#10059</a></li>
<li>fix(model): return deep cloned value for toJSON <a href="https://github.com/sequelize/sequelize/pull/10058">#10058</a></li>
<li>fix(model): create instance with many-to-many association with extra column (#10034) <a href="https://github.com/sequelize/sequelize/pull/10050">#10050</a></li>
<li>fix(query-generator): fix bad property access <a href="https://github.com/sequelize/sequelize/pull/10056">#10056</a></li>
<li>docs(upgrade-to-v4): typo <a href="https://github.com/sequelize/sequelize/pull/10060">#10060</a></li>
<li>docs(model-usage): order expression format <a href="https://github.com/sequelize/sequelize/pull/10061">#10061</a></li>
<li>chore(package): update retry-as-promised to version 3.1.0 <a href="https://github.com/sequelize/sequelize/pull/10065">#10065</a></li>
<li>refactor(scopes): just in time options conforming <a href="https://github.com/sequelize/sequelize/pull/9735">#9735</a></li>
<li>refactor: use sequelize-pool for pooling <a href="https://github.com/sequelize/sequelize/pull/10051">#10051</a></li>
<li>refactor(*): cleanup code <a href="https://github.com/sequelize/sequelize/pull/10091">#10091</a></li>
<li>refactor: use template strings <a href="https://github.com/sequelize/sequelize/pull/10055">#10055</a></li>
<li>refactor(query-generation): cleanup template usage <a href="https://github.com/sequelize/sequelize/pull/10047">#10047</a></li>
</ul><h3>5.0.0-beta.13</h3><ul>
<li>fix: throw on undefined where parameters <a href="https://github.com/sequelize/sequelize/pull/10048">#10048</a></li>
<li>fix(model): improve wrong alias error message <a href="https://github.com/sequelize/sequelize/pull/10041">#10041</a></li>
<li>feat(sqlite): CITEXT datatype <a href="https://github.com/sequelize/sequelize/pull/10036">#10036</a></li>
<li>fix(postgres): remove if not exists and cascade from create/drop database queries <a href="https://github.com/sequelize/sequelize/pull/10033">#10033</a></li>
<li>fix(syntax): correct parentheses around union <a href="https://github.com/sequelize/sequelize/pull/10003">#10003</a></li>
<li>feat(query-interface): createDatabase / dropDatabase support <a href="https://github.com/sequelize/sequelize/pull/10027">#10027</a></li>
<li>feat(postgres): CITEXT datatype <a href="https://github.com/sequelize/sequelize/pull/10024">#10024</a></li>
<li>feat: pass uri query parameters to dialectOptions <a href="https://github.com/sequelize/sequelize/pull/10025">#10025</a></li>
<li>docs(query-generator): remove doc about where raw query <a href="https://github.com/sequelize/sequelize/pull/10017">#10017</a></li>
<li>fix(query): handle undefined field on unique constraint error <a href="https://github.com/sequelize/sequelize/pull/10018">#10018</a></li>
<li>fix(model): sum returns zero when empty matching <a href="https://github.com/sequelize/sequelize/pull/9984">#9984</a></li>
<li>feat(query-generator): add startsWith, endsWith and substring operators <a href="https://github.com/sequelize/sequelize/pull/9999">#9999</a></li>
<li>docs(sequelize): correct jsdoc annotations for authenticate <a href="https://github.com/sequelize/sequelize/pull/10002">#10002</a></li>
<li>docs(query-interface): add bulkUpdate docs <a href="https://github.com/sequelize/sequelize/pull/10005">#10005</a></li>
<li>fix(tinyint): ignore params for TINYINT on postgres <a href="https://github.com/sequelize/sequelize/pull/9992">#9992</a></li>
<li>fix(belongs-to): create now returns target model <a href="https://github.com/sequelize/sequelize/pull/9980">#9980</a></li>
<li>refactor(model): remove .all alias <a href="https://github.com/sequelize/sequelize/pull/9975">#9975</a></li>
<li>perf: fix memory leak due to instance reference by isImmutable <a href="https://github.com/sequelize/sequelize/pull/9973">#9973</a></li>
<li>feat(sequelize): dialectModule option <a href="https://github.com/sequelize/sequelize/pull/9972">#9972</a></li>
<li>fix(query): check valid warn message <a href="https://github.com/sequelize/sequelize/pull/9948">#9948</a></li>
<li>fix(model): check for own property when overriding association mixins <a href="https://github.com/sequelize/sequelize/pull/9953">#9953</a></li>
<li>fix(create-table): support for uniqueKeys <a href="https://github.com/sequelize/sequelize/pull/9946">#9946</a></li>
<li>refactor(transaction): remove autocommit mode <a href="https://github.com/sequelize/sequelize/pull/9921">#9921</a></li>
<li>feat(sequelize): getDatabaseName <a href="https://github.com/sequelize/sequelize/pull/9937">#9937</a></li>
<li>refactor: remove aliases <a href="https://github.com/sequelize/sequelize/pull/9933">#9933</a></li>
<li>feat(belongsToMany): override unique constraint name with uniqueKey <a href="https://github.com/sequelize/sequelize/pull/9914">#9914</a></li>
<li>fix(postgres): properly disconnect connections <a href="https://github.com/sequelize/sequelize/pull/9911">#9911</a></li>
<li>docs(instances.md): add section for restore() <a href="https://github.com/sequelize/sequelize/pull/9917">#9917</a></li>
<li>docs(hooks.md): add warning about memory limits of individual hooks <a href="https://github.com/sequelize/sequelize/pull/9881">#9881</a></li>
<li>fix(package): update debug to version 4.0.0 <a href="https://github.com/sequelize/sequelize/pull/9908">#9908</a></li>
<li>feat(postgres): support ignoreDuplicates with ON CONFLICT DO NOTHING <a href="https://github.com/sequelize/sequelize/pull/9883">#9883</a></li>
</ul><h3>5.0.0-beta.12</h3><ul>
<li>fix(changeColumn): normalize attribute <a href="https://github.com/sequelize/sequelize/pull/9897">#9897</a></li>
<li>feat(describeTable): support string length for mssql <a href="https://github.com/sequelize/sequelize/pull/9896">#9896</a></li>
<li>feat(describeTable): support autoIncrement for mysql <a href="https://github.com/sequelize/sequelize/pull/9894">#9894</a></li>
<li>fix(sqlite): unable to reference foreignKey on primaryKey <a href="https://github.com/sequelize/sequelize/pull/9893">#9893</a></li>
<li>fix(postgres): enum with string COMMENT breaks query <a href="https://github.com/sequelize/sequelize/pull/9891">#9891</a></li>
<li>fix(changeColumn): use engine defaults for foreign/unique key naming <a href="https://github.com/sequelize/sequelize/pull/9890">#9890</a></li>
<li>fix(transaction): fixed unhandled rejection when connection acquire timeout <a href="https://github.com/sequelize/sequelize/pull/9879">#9879</a></li>
<li>fix(sqlite): close connection properly and cleanup files <a href="https://github.com/sequelize/sequelize/pull/9851">#9851</a></li>
<li>fix(model): incorrect error message for findCreateFind <a href="https://github.com/sequelize/sequelize/pull/9849">#9849</a></li>
</ul><h3>5.0.0-beta.11</h3><ul>
<li>fix(count): duplicate mapping of fields break scopes <a href="https://github.com/sequelize/sequelize/pull/9788">#9788</a></li>
<li>fix(model): bulkCreate should populate dataValues directly <a href="https://github.com/sequelize/sequelize/pull/9797">#9797</a></li>
<li>fix(mysql): improve unique key violation handling <a href="https://github.com/sequelize/sequelize/pull/9724">#9724</a></li>
<li>fix(separate): don't propagate group to separated queries <a href="https://github.com/sequelize/sequelize/pull/9754">#9754</a></li>
<li>fix(scope): incorrect query generated when sequelize.fn used with scopes <a href="https://github.com/sequelize/sequelize/pull/9730">#9730</a></li>
<li>fix(json): access included data with attributes <a href="https://github.com/sequelize/sequelize/pull/9662">#9662</a></li>
<li>(fix): pass offset in UNION'ed queries <a href="https://github.com/sequelize/sequelize/pull/9577">#9577</a></li>
<li>fix(destroy): attributes updated in a beforeDestroy hook are now persisted on soft delete <a href="https://github.com/sequelize/sequelize/pull/9319">#9319</a></li>
<li>fix(addScope): only throw when defaultScope is defined <a href="https://github.com/sequelize/sequelize/pull/9703">#9703</a></li>
</ul><h3>5.0.0-beta.10</h3><ul>
<li>fix(belongsToMany): association.add returns array of array of through records <a href="https://github.com/sequelize/sequelize/pull/9700">#9700</a></li>
<li>feat: association hooks <a href="https://github.com/sequelize/sequelize/pull/9590">#9590</a></li>
<li>fix(bulkCreate): dont map dataValue to fields for individualHooks:true<a href="https://github.com/sequelize/sequelize/pull/9672">#9672</a></li>
<li>feat(postgres): drop enum support <a href="https://github.com/sequelize/sequelize/pull/9641">#9641</a></li>
<li>feat(validation): improve validation for type<a href="https://github.com/sequelize/sequelize/pull/9660">#9660</a></li>
<li>feat: allow querying sqlite_master table <a href="https://github.com/sequelize/sequelize/pull/9645">#9645</a></li>
<li>fix(hasOne.sourceKey): setup sourceKeyAttribute for joins <a href="https://github.com/sequelize/sequelize/pull/9658">#9658</a></li>
<li>fix: throw when type of array values is not defined <a href="https://github.com/sequelize/sequelize/pull/9649">#9649</a></li>
<li>fix(query-generator): ignore undefined keys in query <a href="https://github.com/sequelize/sequelize/pull/9548">#9548</a></li>
<li>fix(model): unable to override rejectOnEmpty <a href="https://github.com/sequelize/sequelize/pull/9632">#9632</a></li>
<li>fix(reload): instance.changed() remains unaffected <a href="https://github.com/sequelize/sequelize/pull/9615">#9615</a></li>
<li>feat(model): column level comments <a href="https://github.com/sequelize/sequelize/pull/9573">#9573</a></li>
<li>docs: cleanup / correct jsdoc references <a href="https://github.com/sequelize/sequelize/pull/9702">#9702</a></li>
</ul><h3>5.0.0-beta.9</h3><ul>
<li>fix(model): ignore undefined values in update payload <a href="https://github.com/sequelize/sequelize/pull/9587">#9587</a></li>
<li>fix(mssql): set encrypt as default false for dialect options <a href="https://github.com/sequelize/sequelize/pull/9588">#9588</a></li>
<li>fix(model): ignore VIRTUAL/getters with attributes.exclude <a href="https://github.com/sequelize/sequelize/pull/9568">#9568</a></li>
<li>feat(data-types): CIDR, INET, MACADDR support for Postgres <a href="https://github.com/sequelize/sequelize/pull/9567">#9567</a></li>
<li>fix: customize allowNull message with notNull validator <a href="https://github.com/sequelize/sequelize/pull/9549">#9549</a></li>
</ul><h3>5.0.0-beta.8</h3><ul>
<li>feat(query-generator): Generate INSERT / UPDATE using bind parameters <a href="https://github.com/sequelize/sequelize/pull/9431">#9431</a> <a href="https://github.com/sequelize/sequelize/pull/9492">#9492</a></li>
<li>performance: remove terraformer-wkt-parser dependency <a href="https://github.com/sequelize/sequelize/pull/9545">#9545</a></li>
<li>fix(constructor): set username, password, database via options in addition to connection string<a href="https://github.com/sequelize/sequelize/pull/9517">#9517</a></li>
<li>fix(associations/belongs-to-many): catch EmptyResultError in set/add helpers <a href="https://github.com/sequelize/sequelize/pull/9535">#9535</a></li>
<li>fix: sync with alter:true doesn't use field name <a href="https://github.com/sequelize/sequelize/pull/9529">#9529</a></li>
<li>fix(UnknownConstraintError): improper handling of error options <a href="https://github.com/sequelize/sequelize/pull/9547">#9547</a></li>
</ul><h3>5.0.0-beta.7</h3><ul>
<li>fix(data-types/blob): only return null for mysql binary null <a href="https://github.com/sequelize/sequelize/pull/9441">#9441</a></li>
<li>fix(errors): use standard .original rather than .__raw for actual error</li>
<li>fix(connection-manager): mssql datatype parsing <a href="https://github.com/sequelize/sequelize/pull/9470">#9470</a></li>
<li>fix(query/removeConstraint): support schemas</li>
<li>fix: use Buffer.from</li>
<li>fix(transactions): return patched promise from sequelize.query <a href="https://github.com/sequelize/sequelize/pull/9473">#9473</a></li>
</ul><h3>5.0.0-beta.6</h3><ul>
<li>fix(postgres/query-generator): syntax error with auto-increment SMALLINT <a href="https://github.com/sequelize/sequelize/pull/9406">#9406</a></li>
<li>fix(postgres/range): inclusive property lost in JSON format <a href="https://github.com/sequelize/sequelize/issues/8471">#8471</a></li>
<li>fix(postgres/range): range bound not applied <a href="https://github.com/sequelize/sequelize/issues/8176">#8176</a></li>
<li>fix(mssql): no unique constraint error thrown for PRIMARY case <a href="https://github.com/sequelize/sequelize/pull/9415">#9415</a></li>
<li>fix(query-generator): regexp operator escaping</li>
<li>docs: various improvements and hinting update</li>
</ul><h3>5.0.0-beta.5</h3><ul>
<li>fix: inject foreignKey when using separate:true <a href="https://github.com/sequelize/sequelize/pull/9396">#9396</a></li>
<li>fix(isSoftDeleted): just use deletedAt as flag</li>
<li>feat(hasOne): sourceKey support with key validation <a href="https://github.com/sequelize/sequelize/pull/9382">#9382</a></li>
<li>fix(query-generator/deleteQuery): remove auto limit <a href="https://github.com/sequelize/sequelize/pull/9377">#9377</a></li>
<li>feat(postgres): skip locked support <a href="https://github.com/sequelize/sequelize/pull/9197">#9197</a></li>
<li>fix(mssql): case sensitive operation fails because of uppercased system table references <a href="https://github.com/sequelize/sequelize/pull/9337">#9337</a></li>
</ul><h3>5.0.0-beta.4</h3><ul>
<li>change(model): setDataValue should not mark null to null as changed <a href="https://github.com/sequelize/sequelize/pull/9347">#9347</a></li>
<li>change(mysql/connection-manager): do not execute SET time_zone query if keepDefaultTimezone config is true <a href="https://github.com/sequelize/sequelize/pull/9358">#9358</a></li>
<li>feat(transactions): Add afterCommit hooks for transactions <a href="https://github.com/sequelize/sequelize/pull/9287">#9287</a></li>
</ul><h3>5.0.0-beta.3</h3><ul>
<li>change(model): new options.underscored implementation <a href="https://github.com/sequelize/sequelize/pull/9304">#9304</a></li>
<li>fix(mssql): duplicate order generated with limit offset <a href="https://github.com/sequelize/sequelize/pull/9307">#9307</a></li>
<li>fix(scope): do not assign scope on eagerly loaded associations <a href="https://github.com/sequelize/sequelize/pull/9292">#9292</a></li>
<li>change(bulkCreate): only support non-empty array as updateOnDuplicate</li>
</ul><h3>5.0.0-beta.2</h3><ul>
<li>change(operators): Symbol operators now enabled by default, removed deprecation warning</li>
<li>fix(model): don't add LIMIT in findOne() queries on unique key <a href="https://github.com/sequelize/sequelize/pull/9248">#9248</a></li>
<li>fix(model): use schema when generating foreign keys <a href="https://github.com/sequelize/sequelize/issues/9029">#9029</a></li>
</ul><h3>5.0.0-beta.1</h3><ul>
<li>fix(postgres): reserved words support <a href="https://github.com/sequelize/sequelize/pull/9236">#9236</a></li>
<li>fix(findOrCreate): warn and handle unknown attributes in defaults</li>
<li>fix(query-generator): 1-to-many join in subQuery filter missing where clause <a href="https://github.com/sequelize/sequelize/issues/9228">#9228</a></li>
</ul><h3>5.0.0-beta</h3><ul>
<li><code>Model.attributes</code> now removed, use <code>Model.rawAttributes</code> <a href="https://github.com/sequelize/sequelize/issues/5320">#5320</a></li>
<li><code>paranoid</code> mode will now treat any record with <code>deletedAt</code> as deleted <a href="https://github.com/sequelize/sequelize/issues/8496">#8496</a></li>
<li>Node 6 and up <a href="https://github.com/sequelize/sequelize/issues/9015">#9015</a></li>
</ul></div>
        <a data-ice="link" href="/v5/manual/upgrade-to-v5.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Working with legacy tables</h1><p>While out of the box Sequelize will seem a bit opinionated it's easy to work legacy tables and forward proof your application by defining (otherwise generated) table and field names.</p><h2>Tables</h2><pre><code class="lang-js"><code class="source-code prettyprint">class User extends Model {}
User.init({
  // ...
}, {
  modelName: 'user',
  tableName: 'users',
  sequelize,
});</code>
</code></pre><h2>Fields</h2><pre><code class="lang-js"><code class="source-code prettyprint">class MyModel extends Model {}
MyModel.init({
  userId: {
    type: Sequelize.INTEGER,
    field: 'user_id'
  }
}, { sequelize });</code>
</code></pre><h2>Primary keys</h2><p>Sequelize will assume your table has a <code>id</code> primary key property by default.</p><p>To define your own primary key:</p><pre><code class="lang-js"><code class="source-code prettyprint">class Collection extends Model {}
Collection.init({
  uid: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true // Automatically gets converted to SERIAL for postgres
  }
}, { sequelize });

class Collection extends Model {}
Collection.init({
  uuid: {
    type: Sequelize.UUID,
    primaryKey: true
  }
}, { sequelize });</code>
</code></pre><p>And if your model has no primary key at all you can use <code>Model.removeAttribute('id');</code></p><h2>Foreign keys</h2><pre><code class="lang-js"><code class="source-code prettyprint">// 1:1
Organization.belongsTo(User, { foreignKey: 'owner_id' });
User.hasOne(Organization, { foreignKey: 'owner_id' });

// 1:M
Project.hasMany(Task, { foreignKey: 'tasks_pk' });
Task.belongsTo(Project, { foreignKey: 'tasks_pk' });

// N:M
User.belongsToMany(Role, { through: 'user_has_roles', foreignKey: 'user_role_user_id' });
Role.belongsToMany(User, { through: 'user_has_roles', foreignKey: 'roles_identifier' });</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/legacy.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Who's using sequelize?</h1><p><a href="http://www.walmartlabs.com/"><img src="/v5/./manual/asset/walmart-labs-logo.png" alt="Walmart labs logo"></a></p><blockquote>
<p>... we are avid users of sequelize (and have been for the past 18 months) (Feb 2017)</p>
</blockquote><p></p><hr>

<p></p><p><a href="https://snaplytics.io"><img src="/v5/./manual/asset/logo-snaplytics-green.png" alt="Snaplytics logo"></a></p><blockquote>
<p>We've been using sequelize since we started in the beginning of 2015. We use it for our graphql servers (in connection with <a href="http://github.com/mickhansen/graphql-sequelize">graphql-sequelize</a>), and for all our background workers.</p>
</blockquote><p></p><hr>

<p></p><p><a href="https://connectedcars.io/"><img src="/v5/./manual/asset/connected-cars.png" alt="Connected Cars logo"></a></p><p></p><hr>

<p></p><p><a href="https://bitovi.com"><img src="/v5/./manual/asset/bitovi-logo.png" alt="Bitovi Logo"></a></p><blockquote>
<p>We have used Sequelize in enterprise projects for some of our Fortune 100 and Fortune 500 clients.  It is used in deployments that are depended on by hundreds of millions of devices every year.</p>
</blockquote><p></p><hr>

<p></p><p><a href="https://www.ermeshotels.com"><img src="/v5/./manual/asset/ermeshotels-logo.png" alt="ErmesHotels Logo"></a></p><blockquote>
<p>Using Sequelize in production for two different apps with 30k+ daily users by 2 years. I doubt there is something better at this moment in terms of productivity and features.</p>
</blockquote></div>
        <a data-ice="link" href="/v5/manual/whos-using.html"></a>
      </div>
    </div>
<div class="manual-card-wrap" data-ice="cards">
      <div class="manual-card">
        <div data-ice="card"><h1>Legal Notice</h1><h2>License</h2><p>Sequelize library is distributed with MIT license. You can find original license <a href="https://github.com/sequelize/sequelize/blob/master/LICENSE">here.</a></p><pre><code class="lang-text"><code class="source-code prettyprint">MIT License

Copyright (c) 2014-present Sequelize contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.</code>
</code></pre><h2>AUTHOR(S)</h2><pre><code class="lang-text"><code class="source-code prettyprint">Main author:

Sascha Depold
Uhlandstr. 160
10719 Berlin
sascha [at] depold [dot] com
[plus] 49 152 [slash] 03878582
</code>
</code></pre><h2>INHALTLICHE VERANTWORTUNG</h2><pre><code class="lang-text"><code class="source-code prettyprint">Ich übernehme keine Haftung für ausgehende Links.
Daher musst du dich bei Problemen an deren Betreiber wenden!</code>
</code></pre></div>
        <a data-ice="link" href="/v5/manual/legal.html"></a>
      </div>
    </div>
</div>
</div>
</div>

<footer class="footer">
  Generated by <a href="https://esdoc.org">ESDoc<span data-ice="esdocVersion">(1.1.0)</span><img src="/v5/./image/esdoc-logo-mini-black.png"></a>
</footer>

<script src="/v5/script/search_index.js"></script>
<script src="/v5/script/search.js"></script>
<script src="/v5/script/pretty-print.js"></script>
<script src="/v5/script/inherited-summary.js"></script>
<script src="/v5/script/test-summary.js"></script>
<script src="/v5/script/inner-link.js"></script>
<script src="/v5/script/patch-for-local.js"></script>


</body></html>